Skip to content

Instantly share code, notes, and snippets.

@JonCanning
Last active May 23, 2017 11:17
Show Gist options
  • Select an option

  • Save JonCanning/3176a06b0e6d4816dea4 to your computer and use it in GitHub Desktop.

Select an option

Save JonCanning/3176a06b0e6d4816dea4 to your computer and use it in GitHub Desktop.
FizzBuzz decision tree
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