12 Oct

# Arithmetic

Basic:

``````> 3 + 4
7

> 1 - 3.5
-2.5

> 4 * (-2)  -- negative literals must be surrounded by parantheses
-8
``````

Division:

``````> 7 / 2
3.5

> 7 `div` 2  -- equivalent to / on ints in C
3

> 7 `mod` 2  -- equivalent to % on ints in C
1  -- reminder after division
``````

Exponentiation:

``````> 2 ** 4
16

> 2 ^ 4
16
``````

# Function signatures

Optional, helps in debugging.

``````double :: Int -> Int  -- takes an integer and returns an integer
double x = x + x

square x = x^2  -- x^2 is equivalent to x*x
``````

Multiple arguments:

``````customAdd :: Int -> Int -> Int  -- takes two integers and returns one
customAdd x y = x + y + 10
``````

After declaring a signature `func :: Type -> Type`, you must also write the body of the function, or at least `func = undefined`.

# Calling functions

Parentheses are optional (when they cause no ambiguity):

``````> double(10)
20

> double 10
20
``````

Functions of arity (number of arguments) 2 can be used as an infix operator:

``````> div 100 2
50

> 100 `div` 2  -- function name surrounded by backticks
50
``````

# Conditionals

The following are equivalent:

``````-- variant 1: if
fact n = if n == 0 then 1
else n * fact(n-1)

-- variant 2: equations
fact 0 = 1
fact n = n * fact(n-1)

-- variant 3: cases
fact n
| n == 0      = 1
| otherwise   = n * fact(n-1)  -- otherwise is alias for True
``````

Implied:

``````isDivisible x = x `mod` 3 == 0  -- implied form of:
isDivisible x = if x `mod` 3 == 0 then True else False
``````