Many languages have a concept of Null. OCaml uses option to express "presence or absence" of data.
Defining Option
type 'a option =
| None
| Some of 'a
You don’t need to define this in practice — use the standard library’s version.
Example
let what_number_am_i_thinking (my_number : int option) =
match my_number with
| None -> "I'm not thinking of any number!"
| Some number -> "My number is: " ^ Int.to_string number
Tests
let%test _ = String.(=) (what_number_am_i_thinking None) "I'm not thinking of any number!"let%test _ = String.(=) (what_number_am_i_thinking (Some 7)) "My number is: 7"
Your Turn: Safe Division
Return None if divisor is zero, otherwise return Some result.
let safe_divide ~dividend ~divisor =
failwith "For you to implement"
let%test "Testing safe_divide..." =
match safe_divide ~dividend:3 ~divisor:2 with
| Some 1 -> true
| _ -> false
let%test "Testing safe_divide..." =
match safe_divide ~dividend:3 ~divisor:0 with
| None -> true
| _ -> false
Your Turn: Option Concatenation
If both inputs are Some, return Some (concatenated string), otherwise return None.
let option_concatenate string1 string2 = failwith "For you to implement"
Tests
let%test "Testing option_concatenate..." =
match option_concatenate (Some "hello") (Some "world") with
| Some "helloworld" -> true
| _ -> false
let%test "Testing option_concatenate..." =
match option_concatenate None (Some "world") with
| None -> true
| _ -> false
let%test "Testing option_concatenate..." =
match option_concatenate (Some "hello") None with
| None -> true
| _ -> false