Dénombrement avec CAML

Calcul des coefficients binomiaux et visualisation du triangle de Pascal et du triangle de Sierpinski associé:

OCaml
(* avec la relation de Pascal ; C(n,p) = C(n-1,p) + C(n-1,p-1)*)
let rec binom0 = fun n p ->
  if p > n || n < 0 || p < 0 then
    0
  else
    if p = 0 then
      1
    else
      binom0 (n-1) p + binom0 (n-1) (p-1);;
 
(* on utilise C(n,p) = (n-p+1)/p * C(n,p-1) → acc_n = (num -1)*acc_{n-1}/(den + 1) et acc_0 = 1 *)
let binom = fun n p ->
   if p > n || n < 0 || p < 0 then
     0
   else
     let rec aux = fun acc num den ->
       if den <= p then
         aux ((acc * num) / den) (num - 1) (den + 1)
       else
         acc
     in aux 1 n 1;;
 
(*------------------les étoiles---------------*)
let triangle1 n =
for i = 0 to n do
  for j = 0 to i do
    print_int (binom i j);
    print_string " "
  done;
  print_newline ()
done;;
 
let triangle2 n =
  let t = Array.make_matrix (n+1) (n+1) 0 in
  t.(0).(0) <- 1;
  for i = 1 to n do
    t.(i).(0) <- 1;
    for j = 1 to i do
      t.(i).(j) <- t.(i-1).(j-1) + t.(i-1).(j);
    done;
  done;
  t;;
 
let binom2 n p =
  let b = triangle2 n in
  b.(n).(p);;
 
let triangle3 n =
for i = 0 to n do
  for j = 0 to i do
    let b = binom i j in
    if b mod 2 = 0 then print_string " "
    else print_string "*"
  done;
  print_newline ()
done;;
 
let triangle4 n =
  let t = triangle2 n in
  for i = 0 to n do
    for j = 0 to i do
      let b = t.(i).(j) in
      if b mod 2 = 0 then print_string " "
      else print_string "*"
    done;
    print_newline ()
  done;;

courtesy of webmatter.de