Jane Street OCaml Challenge: Recursion

Functions in OCaml can call themselves — but only if marked with rec.

This will give a compilation error:

let add_every_number_up_to x = assert (x >= 0); match x with | 0 -> 0 | _ -> x + add_every_number_up_to (x - 1)

Fix it by changing let to let rec.

Recursive Sum

This function sums all numbers up to x.

let rec add_every_number_up_to x = assert (x >= 0); match x with | 0 -> 0 | _ -> x + add_every_number_up_to (x - 1)

Now You Try: Recursive Factorial

let rec factorial x = assert (x >= 0); failwith "For you to implement"

Tests for factorial

let%test "Testing factorial..." = Int.( = ) 1 (factorial 0) let%test "Testing factorial..." = Int.( = ) 120 (factorial 5) let%test "Testing factorial..." = Int.( = ) 479001600 (factorial 12)