User Tools

Site Tools


cs_lang:ocaml

This is an old revision of the document!


Learning Objective Caml

Simple examples

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::t -> (x mod 2 == 0)::(func t);;
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;;
cs_lang/ocaml.1310457479.txt.gz · Last modified: 2011/07/12 09:57 by cedric