Skip to content

Instantly share code, notes, and snippets.

@n8gray

n8gray/sample.ml

Created Feb 22, 2016
Embed
What would you like to do?
(* This is the original function. It works fine, but makes extra calls to check_left and check_right. *)
let sorting_hat id =
if not (base_case id) then Dead
else
begin
if check_left id && check_right id then Central
else if check_left id then Left
else if check_right id then Right
else Dead
end
(*
One technique that OCaml newbies often overlook is using pattern matching against the components of a
tuple to test multiple values at once. This can give you the ability to convert many long "else if"
chains to elegant match expressions. This function is a good candidate for this approach, since it's
really just a case analysis over the results of check_left and check_right.
Here's a version that uses this technique. The code only evaluates check_left and check_right once.
As a bonus, the mutually exclusive case analysis jumps right out at you.
*)
let sorting_hat id =
if not (base_case id) then Dead
else match (check_left id), (check_right id) with
| true, true -> Central
| true, false -> Left
| false, true -> Right
| _ -> Dead
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment