All of these together makes it easy to express your problem as a set of cases, which you can then decompose and compose to write your logic.
(* examples/pattern-fun.sml *)