Wiki2
Currying

Order of parameters and currying

I got really confused when reading A Gentle Introduction To Haskell, version 98 (page 10, Functions), which aim to explain currying as the first concept of describing functions.

  • Type definitions with -> operator is right associative.
  • Function calls with parameters separated by space (“ ”) are left associative.
  • Parameters are ordered from left to right both in type definitions and function calls.

For example see the type definition of div.

> :t div
:: (Integral a) => a -> a -> a
  • Numbering the parameters, a1 -> a2 -> a3
  • Using right associative rule for -> operator, a1 -> (a2 -> a3)

So the type definition roughly translates to:

  1. A value of a1 applied to function div evaluates a function
  2. A value of type a2 applied to this function evaluates to a value of type a3

Calling divwith parameters 10 and 2 give the result 5.

> div 10 2
=> 5
  • Using left associative rule for parameters in function calls, (div 10) 2

This means that the function returned by applying 10 to div translates to 10/x. 2 applied to this function evaluates to 5. 10 is of type a1, 2 of type a2 and 5 of type a3.

The infix operator of div works in the same manner.

> :t (/)
:: (Fractional a) => a -> a -> a

> (/) 10 2
=> 5.0

> 10 / 2
=> 5.0

> 10 `div` 2
=> 5

So the div can be defined as.

div a b = a / b

Note also that operators can have different priority and “associativeness”. This is defined by infix, infixl and infixr functions. But functions and -> in type definitions work as explained above.

The “function application” operator, $, can be used to change the left associative rule for function argument application.

f $ x = f x

One example where you want to apply several functions at the same time and want to avoid parentheses.

Prelude> let inc = (+) 1
Prelude> inc div 10 2
    The function `inc' is applied to three arguments,
Prelude> inc $ div 10 2
6
Prelude> inc (div 10 2)

So you can make multiple function applications right associative.

References

Also see Lambda Calculus: Motivation for an mathematical example of currying.