5 people like it.

FizzBuzz with Rule Engine

Inspired by http://dave.fayr.am/posts/2012-10-4-finding-fizzbuzz.html Rules are in a list of lambdas that can be easily modified. A pattern-matching recursive function applies them in the correct order.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
let fizzRules = 
    [
        (fun i -> if i % 3 = 0 then "Fizz" else "")
        (fun i -> if i % 5 = 0 then "Buzz" else "")
        (fun i -> if i % 7 = 0 then "Bazz" else "")
        (fun i -> if i % 11 = 0 then "Bop" else "")
    ]

let fizzBuzz rules i =
    let rec ruleRunner s rl =
        match s, rl with
            | "", []
                ->  i.ToString()
            | _, []
                ->  s
            | _, h::t
                ->  ruleRunner (s + h i) t
    ruleRunner "" rules

[ 1 .. 105 ]
    |> Seq.map (fizzBuzz fizzRules)
    |> Seq.iter (printfn "%s")
val fizzRules : (int -> string) list

Full name: Script.fizzRules
val i : int
val fizzBuzz : rules:('a -> string) list -> i:'a -> string

Full name: Script.fizzBuzz
val rules : ('a -> string) list
val i : 'a
val ruleRunner : (string -> ('a -> string) list -> string)
val s : string
val rl : ('a -> string) list
System.Object.ToString() : string
val h : ('a -> string)
val t : ('a -> string) list
module Seq

from Microsoft.FSharp.Collections
val map : mapping:('T -> 'U) -> source:seq<'T> -> seq<'U>

Full name: Microsoft.FSharp.Collections.Seq.map
val iter : action:('T -> unit) -> source:seq<'T> -> unit

Full name: Microsoft.FSharp.Collections.Seq.iter
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn

More information

Link:http://fssnip.net/e7
Posted:5 years ago
Author:Richard Broida
Tags: fizzbuzz , kata , rules , recursion , pattern matching , lambdas