{
I had previously done a solution for FizzBuzz in F# (from a long time ago) but now that I’m more familiar with the idioms of F# I tend more towards pattern matching instead of if/else logic for quite a few scenarios. Here is an example of my rewriting what could otherwise been a conditional if/else checking for factors of 3 and 5, but using a pattern match instead.
#light
let fizz num =
match (num % 3 = 0) with
| true -> "fizz"
| false -> ""
let buzz num =
match (num % 5 = 0) with
| true -> "buzz"
| false -> ""
let outform num fizCalc =
match fizCalc.ToString().Length = 0 with
| true -> num.ToString()
| false -> fizCalc
let rec printer nums =
match nums with
| [] -> printfn "-"
| h::t ->
printfn "%s" (outform h ((fizz h) + (buzz h)))
printer t
let numbers = [1..100]
printer numbers
Although I read claims that if/else conditional operations are more readable, I think the pattern match used consistently across scenarios above makes for something I find quite readable.
No comments:
Post a Comment