joost

personal web page

6 February 2025

haskell: values, functions, currying, partial application and eta-reduction

values and functions

a = 5

Here the symbol a is assigned with the value 5.

a = 2 + 3

Here the symbol a is assigned with the result of calculating 2 + 2, which also is 5.

sum x y = x + y
a = sum 2 3

Here the symbol sum is defined as a function that takes two arguments and returns the sum of those two numbers. The value a is assigned to the result of calling sum with arguments 2 and 3, which calculates 2 + 3, which is still 5.

currying

addThree x = sum 3 x

Here we define a new function addThree that is defined as calling our earlier sum function with 3 and x.

addThree x = (sum 3) x

Here we have rewritten addThree in curried form. This means that sum is first called with 3 as argument, and the result of that is a new function that takes only one argument and we call that function with argument x. In general calling a function with many arguments can be seen as calling that function with the first argument, then the result of that with the second argument, etc.

Another way to think about it is to have the sum function rewritten like this, returning a function that only takes one argument and return a new function that takes another argument:

sum x = (\y -> x + y)

a = sum 2 3

That sum function can still be called with two arguments, where the second argument is passed on to the new function returned by sum.

partial application

sum 3 is called a partial application of sum with 3. The result of that partial application is a function that takes only one argument and returns that argument + 3.

eta-reduction

If you think about it, sum 3 is exactly what our addThree function is supposed to do. Because of this we can simplify the definition with a process that is called eta-reduction.

addThree = sum 3

Here we define a new name addThree for the function sum 3 which is the function which takes one argument and returns that argument incremented by 3.

sum = (+)

In a simular way we can define our sum function from earlier just as being equal to the + operator. We have to add the () to make it infix.

addthree = (+ 3)

Finally we can also define our addThree function directly based on +.

summary

All of these concepts will start to make more sense when writing more complex programs.

We look at the same concepts in python in the next post.

After that we look at the same concepts in rust.

tags: haskell