[Haskell-beginners] Confusion over currying, , lambda, and closures
Francesco Ariis
fa-ml at ariis.it
Thu Dec 24 04:37:22 UTC 2020
Il 23 dicembre 2020 alle 21:12 Lawrence Bottorff ha scritto:
> I have these three versions of addition
>
> addA x y = x + y
> addB x = \y -> x + y
> addC = \x -> \y -> x + y
>
> […]
>
> I can't see how addB and addC are actually accomplishing this. addA is
> currying, which I don't fully follow.
Parameters on the left-hand side of a function definition can always be
expressed as a lambda, by «plucking» them from the rightmost one
addA x y = x + y
addA x = \y -> x + y
addA = \x -> \y -> x + y -- those three are equal!
Intuitively you can say that first we are binding the patterns in the
function definition and then the one left in the lambda right-hand side
(if any). So:
add 3 5
addA x = \y -> x + y 3 5
\y -> 3 + y 5
3 + 5
I suspect what the book is trying to teach you is that you can partially
apply a function and pass it around merrily:
map (addA 3) [1, 2, 3]
So by writing `addA 3` we obtain:
addA :: Int -> Int -> Int
addA :: Int -> (Int -> Int) -- can also be written like this
-- since `(->)` is associates to
-- the right
add3 :: Int -> Int -- applying addA to 3
another function with one parameter less. Once everything is applied, you
will get your result!
More information about the Beginners
mailing list