Jane Street OCaml Challenge: Pattern Matching
match ... with
lets us compare values to patterns.
let is_superman x =
match x with
| "Clark Kent" -> true
| _ -> false
You can also match on multiple values at once:
let is_same_person x y =
match x, y with
| "Clark Kent", "Superman"
| "Peter Parker", "Spiderman" -> true
| _ -> false
Your Turn
Write a function using pattern matching that returns true if a number is non-zero.
let non_zero x = failwith "For you to implement"
Tests for non_zero
let%test "Testing non_zero..." = Bool.( = ) false (non_zero 0)
let%test "Testing non_zero..." = Bool.( = ) true (non_zero 500)
let%test "Testing non_zero..." = Bool.( = ) true (non_zero (-400))
Now Match on Two Values
Write a function that returns true if both inputs are non-zero.
let both_non_zero x y = failwith "For you to implement"
Tests for both_non_zero
let%test "Testing both_positive..." = Bool.( = ) false (both_non_zero 0 0)
let%test "Testing both_positive..." = Bool.( = ) false (both_non_zero 0 1)
let%test "Testing both_positive..." = Bool.( = ) false (both_non_zero (-20) 0)
let%test "Testing both_positive..." = Bool.( = ) true (both_non_zero 400 (-5))