3

I have the following code which gives out [2,4,6] :

j :: [Int]
j = ((\f x -> map x) (\y -> y + 3) (\z -> 2*z)) [1,2,3]

Why? It seems that just the "z-function" is being used, what happens to the "y-function"? And how does map work in this particular case?

1 Answer 1

6

Let's compute:

((\f x -> map x) (\y -> y + 3) (\z -> 2*z)) [1,2,3]
                 ^^^ f ^^^^^^^ ^^^ x ^^^^^
=
(map x) [1,2,3]
   where f = \y -> y +3
         x = \z -> 2*z
=
[x 1,x 2,x 3]
   where f = \y -> y +3
         x = \z -> 2*z
=
[2*1,2*2,2*3]
   where f = \y -> y +3
         x = \z -> 2*z
=
[2,4,6]
   where f = \y -> y +3
         x = \z -> 2*z

As we can see, f was taken as an argument, but was never used after that. Consequently \y -> y+3 never affected the final result.

The function map x is the function that applies function x to each element of a list. Note that, above, (map x) [1,2,3] is the same as map x [1,2,3]. Indeed, each function application g x1 x2 x3 x4 can be equivalently written as (((g x1) x2) x3) x4 by left-associating the applications.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for that really good explanation!

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.