cs_lang:ocaml

# Presentation

## Typing discipline

• static typed;
• strongly typed;
• inferred.

# Simple examples

## Increment a number

```# let inc n = n+1;;
val inc : int -> int = <fun>

# inc 2;;
- : int = 3

# Alternative:
# let inc = (+) 1;;
val inc : int -> int = <fun>```

### Equivalent in Python

```>>> def inc(n):
...     return n+1

>>> inc(2)
3```

## Great common divisor

```# let rec gcd a b = match (a mod b) with
| 0 -> b
| c -> gcd b c;;
val gcd : int -> int -> int = <fun>

# gcd 77 42;;
- : int = 7```

### Equivalent in Python

```def gcd(a, b):
while b != 0:
(a, b) = (b, a%b)
return a```

## Parity

```let rec parity = function
| [] -> []
| x::l -> (x mod 2 == 0)::(parity l);;
val func : int list -> bool list = <fun>

parity [1;2;3;4;5;6;7;8;9];;
- : bool list = [false; true; false; true; false; true; false; true; false]```

### Equivalent in Python

```>>> l = [1,2,3,4,5,6,7,8,9]
>>> [(a % 2 == 0) for a in l]
[False, True, False, True, False, True, False, True, False]```

## Ackermann

```let rec ackermann x y = match (x,y) with
| (0, _) -> y + 1
| (_ , 0) -> ackermann (x - 1) 1
| (_, _) -> ackermann (x - 1) (ackermann x (y - 1));;```

### Equivalent in Python

```def ackermann(m, n):
if m == 0:
return n + 1
elif n == 0:
return ackermann(m - 1, 1)
else:
return ackermann(m - 1, ackermann(m, n - 1))```

## Factorielle

```let rec factorielle = function
0 -> 1
| n -> n * factorielle (n - 1) ;;```
```(* Longueur d'une liste *)
# let rec longueur = function
[] -> 0
| t :: q -> 1 + longueur q ;;```
```let rec exists p = function
[] -> false
| a::l -> p==a || exists p l;;```