5

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])
1
  • 4
    Can you be a bit more specific? What do you understand about this, and what part is confusing you? Commented Feb 17, 2019 at 20:05

1 Answer 1

5

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 xs 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]
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the explicit answer, still one tiny question, if I might ask. why does x+a result in (+a), what's the x and where did it go?
@SvenKuffer: this is more simplified notation. This is called "operator section" iirc: wiki.haskell.org/Section_of_an_infix_operator so behind the curtains, it is still \x -> x+a, but this would result in our list in a lot of lambda expressions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.