Home > database >  function that input an integer and return a function in Haskell
function that input an integer and return a function in Haskell

Time:12-02

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?

CodePudding user response:

You are looking at a curried function. The code

getAddFunc x y = x   y

is equivalent to

getAddFunc x = \y -> x   y

i.e., taking x as argument and returning a function of y.

This can also be written

getAddFunc = \x -> \y -> x   y

or

getAddFunc = \x y -> x   y

In Haskell, from a technical point of view, every function takes exactly one argument. However, after taking that argument, it can return another function taking as input a "second" argument. This mechanism can also be interpreted as a function taking "two" arguments. This further generalizes to N arguments in a similar way.

CodePudding user response:

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.

  • Related