Reputation: 45
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?
Upvotes: 3
Views: 78
Reputation: 116139
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.
Upvotes: 6