Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand the "Currying" in Haskell?

Tags:

haskell

Assume there is a function called "smallerc"

    smallerc :: Integer -> (Integer->Integer)
    smallerc x y = if x <=y then x else y

Why not declare the function by using:

    smallerc :: (Integer -> Integer) ->Integer

Thank you!

like image 216
XIA Yang Avatar asked Dec 20 '25 04:12

XIA Yang


1 Answers

The key to understanding currying is to understand that there is no such thing as a function with more than one argument. Every function in haskell has exactly one argument. But because of the right-associative properties of the -> operator, that's not immediately clear.

When you see this:

Integer -> Integer -> Integer

It is equivalent to this:

Integer -> (Integer -> Integer)

In both cases, the function takes an Integer and returns a function. (The function returned is one that takes an Integer and returns an Integer.) So this might be something like a simple mathematical operation; it takes an Integer (let's say 5) and returns a function that takes another Integer (5 again) and adds it to the first one, and returns the result (10).

But when you do this:

(Integer -> Integer) -> Integer

You've created something very different -- a function that takes a function and returns an Integer. This could also be a way of implementing a mathematical function; but instead of taking an Integer as the first argument, it takes the mathematical operation itself! So for example, say you pass to this function a function that adds 5 to whatever is passed to it. This function then passes 5 to that function, and returns the result (10).

like image 95
senderle Avatar answered Dec 22 '25 21:12

senderle