Last active
March 3, 2016 12:13
-
-
Save alexfoxgill/1ccdb406e15eb474191a to your computer and use it in GitHub Desktop.
Small F# script demonstrating extensible FizzBuzz implementation
This file contains 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
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