Jane Street OCaml Challenge: Higher-Order Functions
Let's define a function that adds 1 to any number:
let add1 x = failwith "For you to implement"
Now define a square function:
let square x = failwith "For you to implement"
First-Class Functions
Functions in OCaml are first-class — they can be passed around just like values.
Implement a function twice
that applies a given function twice:
let twice f x = failwith "For you to implement"
Use twice
to implement:
let add2 = failwith "For you to implement" (* Hint: use add1 *)
let raise_to_the_fourth = failwith "For you to implement" (* Hint: use square *)
Tests
let%test "Testing add1..." = Int.(=) 5 (add1 4)
let%test "Testing square..." = Int.(=) 16 (square 4)
let%test "Testing square..." = Int.(=) 16 (square (-4))
let%test "Testing add1..." = Int.(=) 5 (twice add1 3)
let%test "Testing add2..." = Int.(=) 1337 (add2 1335)
let%test "Testing raise_to_the_fourth..." = Int.(=) 1 (raise_to_the_fourth 1)
let%test "Testing raise_to_the_fourth..." = Int.(=) 10000 (raise_to_the_fourth 10)