Reputation: 81
I've got this expression in Haskell, now I don't understand exactly how this is applied. Typing in j returns [2,3,4]
j :: [Int]
j = map (\a -> a 1) (map (\a x -> x + a) [1,2,3])
Upvotes: 5
Views: 5291
Reputation: 476567
There are two maps here, let us first analyze the subexpression:
map (\a x -> x + a) [1,2,3]
We can write the lambda expression in a form that is probably better for the above case:
map (\a -> (\x -> x + a)) [1,2,3]
So this is a function that takes a parameter a
and returns a function. So it will return a function that takes a parameter x
that maps to x + a
. Thus that means that the second map
produces a list of functions. Indeed, so the above expression is equivalent to:
[(+1), (+2), (+3)]
or more verbose:
[\x -> x+1, \x -> x+2, \x -> x+3]
here the x
s in the lambda expressions are different variables.
Now the first map takes these functions, and maps these on calling the function with value one, so, this expression:
map (\a -> a 1) [(+1), (+2), (+3)]
is equivalent to:
[(+1) 1, (+2) 1, (+3) 1]
and thus equivalent to:
[2,3,4]
as you found out.
We can syntactically simplify this function to:
j :: Num a => [a]
j = map ($ 1) (map (+) [1,2,3])
which is semantically equivalent to:
j :: Num a => [a]
j = map (+1) [1,2,3]
and hence:
j :: Num a => [a]
j = [2,3,4]
Upvotes: 5