Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial application left to right

I started with haskell yesterday and am still completely lost on the shore of this brave new world. Now I have run into the following issue:

Let's assume I have some function that does some magic to an integer and another variable:

makeTuple :: Int -> a -> (Int, a)
makeTuple n x = (n, x)

Now I want to apply this function to all elements of a list. So far no problem, as mapping is your daily bread and butter in python (where I come from), too.

makeTupleList :: Int -> [a] -> [ (Int, a) ]
makeTupleList n x = map (makeTuple n) x

As far as I understand, the binary function makeTuple is applied partially with the integer n and hence becomes a unary function which can be mapped to each element of x. So far, all is well.

But what do I do when the makeTuple function has another signature, like:

makeTuple2 :: a -> Int -> (Int, a)
makeTuple2 x n = (n, x)

Many ways lead to Rome: the effect is the same, but the way is another. Now obviously the mapping doesn't work anymore: The function expects an Int and gets an a.

makeTupleList2 :: Int -> [a] -> [ (Int, a) ]
makeTupleList2 n x = map (makeTuple2 n) x -- boolshit

This was to be expected. My -maybe too pythonic- workaround is using another function to pass the parameters where they should go:

makeTupleList2 :: Int -> [a] -> [ (Int, a) ]
makeTupleList2 n x = map (\x -> makeTuple2 x n) x

Question: What is the preferred functional, haskell-style way of partially applying functions when the parially applied parameters isn't the leftmost?

like image 440
Hyperboreus Avatar asked Jul 16 '11 14:07

Hyperboreus


1 Answers

You can use flip, which swaps the first and second arguments of a function.

makeTupleList2 n x = map (flip makeTuple2 n) x

Another option is to use the backticks syntax to make an infix operator and then partially apply that using an operator section.

maleTupleList2 n x = map (`makeTuple2` n) x

Or, as you said we can use a lambda expression. Which one to use depends on context and personal taste. Use whatever you feel is most clear.


PS: What you're doing is called partial application. Currying is the process of transforming a function taking multiple arguments (a, b) -> c into curried form a -> b -> c so that it can be partially applied.

like image 89
hammar Avatar answered Oct 01 '22 02:10

hammar