Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Feed elements of a tuple to a function as arguments in Haskell?

Tags:

In my Haskell program, I want to use printf 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?

like image 900
davidscolgan Avatar asked Feb 25 '11 13:02

davidscolgan


People also ask

Can a function take a tuple as an argument?

A tuple can also be passed as a single argument to the function. Individual tuples as arguments are just individual variables.

How do you get the second element of a tuple Haskell?

2. snd. This tuple function is used to get the second element from the tuple values or group. We can use this function before the tuple and it will return us the second element as the result in Haskell.

How many arguments does tuple take?

A tuple can be an argument, but only one - it's just a variable of type tuple . In short, functions are built in such a way that they take an arbitrary number of arguments.


1 Answers

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)] 
like image 158
Miikka Avatar answered Sep 19 '22 14:09

Miikka