0 people like it.

FizzBuzz with Forward Composition

This version of FizzBuzz uses forward composition instead of recursive pattern matching (see http://fssnip.net/e7). All the rules, including the default case, are in a list of lambdas that can be easily modified. The function executeRules composes the list into a single rule and executes it.

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

let executeRules rules accum i =
    let allRules =
        rules
            |> Seq.map (fun f -> f i)
            |> Seq.reduce ((fun x -> x) (>>))
    allRules accum

let fizzBuzz = executeRules fizzRules ""

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

Full name: Script.fizzRules
val i : int
val s : string
System.Int32.ToString() : string
System.Int32.ToString(provider: System.IFormatProvider) : string
System.Int32.ToString(format: string) : string
System.Int32.ToString(format: string, provider: System.IFormatProvider) : string
val executeRules : rules:seq<('a -> 'b -> 'b)> -> accum:'b -> i:'a -> 'b

Full name: Script.executeRules
val rules : seq<('a -> 'b -> 'b)>
val accum : 'b
val i : 'a
val allRules : ('b -> 'b)
module Seq

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

Full name: Microsoft.FSharp.Collections.Seq.map
val f : ('a -> 'b -> 'b)
val reduce : reduction:('T -> 'T -> 'T) -> source:seq<'T> -> 'T

Full name: Microsoft.FSharp.Collections.Seq.reduce
val x : (('b -> 'b) -> ('b -> 'b) -> 'b -> 'b)
val fizzBuzz : (int -> string)

Full name: Script.fizzBuzz
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
Raw view Test code New version

More information

Link:http://fssnip.net/e8
Posted:12 years ago
Author:Richard Broida
Tags: fizzbuzz , kata , rules , function composition , lambdas