1

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?

3
  • 2
    does it make more sense after reading this? Commented Dec 1, 2021 at 21:23
  • 3
    It's the beauty of haskell Commented Dec 1, 2021 at 21:32
  • 1
    @ShamPooSham just start that beauty journey for 40 min :) Commented Dec 1, 2021 at 21:35

2 Answers 2

4

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.

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

Comments

3

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.

Comments

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.