1 people like it.

Fun with FizzBuzz

Lazily generate fizzbuzz results and provide a test function. Parameterize the inputs and predicates.

Generate a FizzBuzz result set given two predicates and a max value

1: 
2: 
3: 
4: 
5: 
6: 
7: 
8: 
9: 
let getFizzBuzz pred1 pred2 (n: int) =
    match pred1 n, pred2 n with
    | 0,0 -> "FizzBuzz"
    | 0,_ -> "Fizz"
    | _,0 -> "Buzz"
    | _   -> string n

let fizzbuzz pred1 pred2 n =
    seq { for x in 1..n -> getFizzBuzz pred1 pred2 x }

Generate the Coding Horror FizzBuzz

1: 
fizzbuzz (fun x -> x%3) (fun x -> x%5) 100 |> Seq.toArray

FizzBuzz tester

1: 
2: 
3: 
4: 
5: 
6: 
let testFizzBuzz n =
    let pred1, pred2 = (fun x -> x%3), (fun x -> x%5)
    getFizzBuzz pred1 pred2 n
        = (fizzbuzz pred1 pred2 n
           |> Seq.skip (n-1)
           |> Seq.head)
val getFizzBuzz : pred1:(int -> int) -> pred2:(int -> int) -> n:int -> string

Full name: Script.getFizzBuzz
val pred1 : (int -> int)
val pred2 : (int -> int)
val n : int
Multiple items
val int : value:'T -> int (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.int

--------------------
type int = int32

Full name: Microsoft.FSharp.Core.int

--------------------
type int<'Measure> = int

Full name: Microsoft.FSharp.Core.int<_>
Multiple items
val string : value:'T -> string

Full name: Microsoft.FSharp.Core.Operators.string

--------------------
type string = System.String

Full name: Microsoft.FSharp.Core.string
val fizzbuzz : pred1:(int -> int) -> pred2:(int -> int) -> n:int -> seq<string>

Full name: Script.fizzbuzz
Multiple items
val seq : sequence:seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Core.Operators.seq

--------------------
type seq<'T> = System.Collections.Generic.IEnumerable<'T>

Full name: Microsoft.FSharp.Collections.seq<_>
val x : int
module Seq

from Microsoft.FSharp.Collections
val toArray : source:seq<'T> -> 'T []

Full name: Microsoft.FSharp.Collections.Seq.toArray
val testFizzBuzz : n:int -> bool

Full name: Script.testFizzBuzz
val skip : count:int -> source:seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Collections.Seq.skip
val head : source:seq<'T> -> 'T

Full name: Microsoft.FSharp.Collections.Seq.head

More information

Link:http://fssnip.net/kO
Posted:11 years ago
Author:Ryan Riley
Tags: fizzbuzz