Feed elements of a tuple to a function as arguments in Haskell?
In my Haskell program, I want to use pri开发者_JAVA百科ntf to format a list of tuples. I can map printf over a list to print out the values one at a time like this:
mapM_ (printf "Value: %d\n") [1,2,3,4]
Value: 1
Value: 2
Value: 3
Value: 4
I want to be able to do something like this:
mapM_ (printf "Values: %d %d\n") [(1,100),(2,350),(3,600),(4,200)]
Values: 1 100
Values: 2 350
Values: 3 600
Values: 4 200
But this passes a tuple to printf, not two separate values. How can I turn the tuple into two arguments for printf?
Function uncurry
converts a two-argument (curried) function into a function on pairs. Here's its type signature:
uncurry :: (a -> b -> c) -> (a, b) -> c
You need to use it on printf
, like this:
mapM_ (uncurry $ printf "Values: %d %d\n") [(1,100),(2,350),(3,600),(4,200)]
Another solution is to use pattern matching to deconstruct the tuple, like this:
mapM_ (\(a,b) -> printf "Values: %d %d\n" a b) [(1,100),(2,350),(3,600),(4,200)]
mapM_ (\(x,y) -> printf "Value: %d %d\n" x y) [(1,100),(2,350),(3,600),(4,200)]
A type-safe alternative to Text.Printf
is the formatting package. Text.Printf.printf
does not ensure at compile-time that the number of formatting parameters aligns with the number of arguments and their types. Read Chris Done's article, What's wrong with printf? for examples.
An example usage:
{-# LANGUAGE OverloadedStrings #-}
import Formatting
map (uncurry $ formatToString ("Value: " % int % " " % int)) [(1,100), (2,350), ...]
map (\(x,y) -> formatToString ("Value: " % int % " " % int) x y) [(1,100), (2,350), ...]
It requires the GHC extension OverloadedStrings to function properly.
While formatToString ("Value: " % int % " " % int)
has the type Int -> Int -> String
, uncurrying it gives the type (Int, Int) -> String
of which the input type matches the elements in the list.
The rewriting process can be broken down; assuming f
= formatString ("Value: " ...)
,
map (\(x,y) -> f x y) ≡ map (\(x,y) -> uncurry f (x,y)) ≡ map (uncurry f)
That is, first you uncurry f to achieve the function that accepts tuples, and then you perform a regular Eta-conversion since \(x,y) -> uncurry f (x,y)
is equivalent to simply uncurry f
. To print each line in the result, use mapM_
:
mapM_ (putStrLn . uncurry $ formatToString ...) [(1,100), (2,350), ...]
If you run hlint YourFile.hs, these rewrites will be recommended to you.
精彩评论