1 people like it.
Like the snippet!
Fun with FizzBuzz
Lazily generate fizzbuzz results and provide a test function. Parameterize the inputs and predicates.
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 }
|
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
|
fizzbuzz (fun x -> x%3) (fun x -> x%5) 100 |> Seq.toArray
(* Results:
val it : string [] =
[|"1"; "2"; "Fizz"; "4"; "Buzz"; "Fizz"; "7"; "8"; "Fizz"; "Buzz"; "11";
"Fizz"; "13"; "14"; "FizzBuzz"; "16"; "17"; "Fizz"; "19"; "Buzz"; "Fizz";
"22"; "23"; "Fizz"; "Buzz"; "26"; "Fizz"; "28"; "29"; "FizzBuzz"; "31";
"32"; "Fizz"; "34"; "Buzz"; "Fizz"; "37"; "38"; "Fizz"; "Buzz"; "41";
"Fizz"; "43"; "44"; "FizzBuzz"; "46"; "47"; "Fizz"; "49"; "Buzz"; "Fizz";
"52"; "53"; "Fizz"; "Buzz"; "56"; "Fizz"; "58"; "59"; "FizzBuzz"; "61";
"62"; "Fizz"; "64"; "Buzz"; "Fizz"; "67"; "68"; "Fizz"; "Buzz"; "71";
"Fizz"; "73"; "74"; "FizzBuzz"; "76"; "77"; "Fizz"; "79"; "Buzz"; "Fizz";
"82"; "83"; "Fizz"; "Buzz"; "86"; "Fizz"; "88"; "89"; "FizzBuzz"; "91";
"92"; "Fizz"; "94"; "Buzz"; "Fizz"; "97"; "98"; "Fizz"; "Buzz"|]
*)
|
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