Totally get lost of the following example that returning a function
getAddFunc :: Int -> (Int -> Int)
getAddFunc x y = x + y
adds3 = getAddFunc 3
fourPlus3 = adds3 4
the function signature Int -> (Int -> Int) told me it accept an Int and function that typed Int -> Int And I am very confused about the function definition x y = x + y, it looks like it took 2 integers x and y rather than just 1 integer! What’s the meaning of x and y here? I am very confused.
Can someone help me with this?
>Solution :
All functions in Haskell take one parameter. Indeed, the function:
getAddFunc x y = x + y
is equivalent to:
getAddFunc x = \y -> x + y
and to:
getAddFunc = \x -> \y -> x + y
You thus construct a function that takes a parameter x, and it maps it to a function that takes a parameter y and will return x + y.
This thus means that getAddFunc 42 is a function that takes a parameter and will add 42 to it.
The (->) type constructor is right associative. Indeed, Int -> (Int -> Int) is the same as Int -> Int -> Int.