Seq.init と Seq.zip で FizzBuzz

判別共用体とアクティブパターンも使いました。結構すっきり書けました。

type FizzBuzz =
| Str of string
| Num of int

[<Test>]
let ``fizzbuzz with Seq.init and Seq.zip``() =

let (|Incr|) n = n + 1
let create num s = Seq.init 100 (function Incr(n) -> if n % num = 0 then Str(s) else Num(n))
let fizz = create 3 "fizz"
let buzz = create 5 "buzz"

Seq.zip fizz buzz
|> Seq.map (function
| Str(f), Str(b) -> f + b
| Str(f), _ -> f
| _ ,Str(b) -> b
| Num(n), _ -> string(n))
|> Seq.iter (printfn "%s")

アクティブパターンは単にインクリメントするだけに使っています。次のコードのように書くのとおんなじなんですが、よりシンプルかなと思って。自分の中では結構使えるパターンになりそう。
let create num s = Seq.init 100 (fun n -> let n = n + 1 in if n % num = 0 then Str(s) else Num(n))