Commits

Joby Poriyath committed 3f465fe

Pascal's Triangle from SICP Ch 1 (for Moolu)

  • Participants
  • Parent commits adafc2b

Comments (0)

Files changed (1)

+(*
+
+  f (n) = n ----------> n < 3
+  f (n) = f (n - 1) + 2 f (n - 2) + 3 f (n - 3) ----------> n >= 3
+  
+*)
+
+let f n =
+  let rec f_aux a b c i n = 
+    if i = n 
+    then c
+    else
+      let d = a + 2 * b + 3 * c in
+      f_aux d a b (i + 1) n
+  in
+  match n with
+    | i when i < 3 -> i
+    | i -> f_aux 2 1 0 0 i
+      
+
+(* Pascal's Triangle *)
+let rec pascal row =
+  match row with
+    | 1 -> [1]
+    | n when n < 1 -> failwith "pascal: invalid argument (row >= 1)"
+    | n -> 
+      let a = 0 :: pascal (row - 1) in
+      let b = List.rev a in
+      List.map2 (+) a b
+        
+        
+let rec print_int_list lst = 
+  match lst with
+    | [] -> print_newline ()
+    | (n :: ns) -> (print_int n ; print_string " "; print_int_list ns)
+
+let rec upto n m = 
+  if n < m 
+  then n :: (upto (n + 1) m)
+  else []
+
+let range n = upto 0 n
+
+let print_pascal last_row = 
+  List.iter print_int_list (List.map pascal (upto 1 (last_row + 1)))
+