Skip to content

Instantly share code, notes, and snippets.

@alexfoxgill
Last active March 3, 2016 12:13
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 alexfoxgill/1ccdb406e15eb474191a to your computer and use it in GitHub Desktop.
Save alexfoxgill/1ccdb406e15eb474191a to your computer and use it in GitHub Desktop.
Small F# script demonstrating extensible FizzBuzz implementation
let combine fs x y = Seq.fold (fun acc f -> acc || f x y) false fs
let matcher f (n, msg) i =
if f n i then
Some msg
else
None
module Option =
let combine op a b =
match a,b with
| Some x, Some y -> Some (op x y)
| None, x | x, None -> x
let eval predicates hits i =
let res =
hits
|> Seq.map (predicates |> combine |> matcher)
|> Seq.map (fun f -> f i)
|> Seq.reduce (Option.combine (+))
match res with
| Some x -> x
| None -> sprintf "%A" i
let isDivisibleBy a b = b % a = 0
let rec contains a b =
if b > 0 then
b % 10 = a || contains (b / 10) a
else
false
let test = eval [isDivisibleBy; contains] [(3, "Fizz"); (5, "Buzz"); (7, "Woof")]
[1..100]
|> Seq.map test
|> Seq.iter (printf "%s")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment