Last active
May 23, 2017 11:17
-
-
Save JonCanning/3176a06b0e6d4816dea4 to your computer and use it in GitHub Desktop.
FizzBuzz decision tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| type Result = | |
| | Text of string | |
| | Number of int | |
| override self.ToString() = | |
| match self with | |
| | Text s -> s | |
| | Number i -> i.ToString() | |
| type Tree = | |
| | Branch of (int -> Result) * Tree | |
| | Leaf of Result | |
| let rule f s = | |
| function | |
| | i when f i -> Text s | |
| | i -> Number i | |
| let fizz = rule (fun i -> i % 3 = 0) "fizz" | |
| let buzz = rule (fun i -> i % 5 = 0) "buzz" | |
| let fizzbuzz = rule (fun i -> i % 3 = 0 && i % 5 = 0) "fizzbuzz" | |
| let lucky = rule (fun i -> i.ToString().Contains "3") "lucky" | |
| let noMatch = string >> Text | |
| let tree = | |
| [ fizz; buzz; fizzbuzz; lucky; noMatch ] | |
| |> List.rev | |
| |> Seq.fold (fun c n -> Branch(n, c)) (Branch (string >> Text, Text "" |> Leaf)) | |
| let rec calculate i tree = | |
| match tree with | |
| | Branch(check, next) -> | |
| match check i with | |
| | Number i -> calculate i next | |
| | r -> r | |
| | Leaf r -> r | |
| { 1..20 } |> Seq.iter (fun i -> calculate i tree |> printfn "%+A") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment