Skip to content

Instantly share code, notes, and snippets.

@n8gray
Created February 22, 2016 20:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n8gray/040de7c533107700f69f to your computer and use it in GitHub Desktop.
Save n8gray/040de7c533107700f69f to your computer and use it in GitHub Desktop.
(* 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