7 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
Next Version Raw view Test code New version

More information

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