Geeks With Blogs
Mark Pearl

 

As per the post I decided to do a F# attempt at FizzBuzz. It took a few seconds…

Using FizzBuzz to Find Developers who Grok Coding..

let FizzBuzz =
    seq {1..100}
    |> Seq.iter (fun x ->
        match x with
           | x when x % 5 = 0 && x % 3 = 0 -> printfn "FizzBuzz"
           | x when x % 3 = 0 -> printfn "Fizz"
           | x when x % 5 = 0 -> printfn "Buzz"           
           | _ -> printfn "%d" x)
Posted on Friday, June 25, 2010 5:48 PM F# | Back to top


Comments on this post: F# FizzBuzz

# re: F# FizzBuzz
Requesting Gravatar...
One minor improvement would be to replace "fun x -> match x with" with the "function" keyword.
Left by Keith on Jun 25, 2010 7:08 PM

# re: F# FizzBuzz
Requesting Gravatar...
You could make your code slightly shorter by replacing "fun x -> match x with" with "function", and also replacing "x % 5 = 0 && x % 3 = 0" with "x % 15 = 0".
Left by Joel on Jun 25, 2010 7:12 PM

# re: F# FizzBuzz
Requesting Gravatar...
Also, not that it matters because this is just Fizz-Buzz, but your code essentially just sets FizzBuzz equal to "unit" with some side-effects that print stuff out. If you want FizzBuzz to have a meaningful value, you can do "let FizzBuzz () =" to turn it into a function. Otherwise, you can just leave off the "let FizzBuzz =" line and get the same effect.
Left by Joel on Jun 25, 2010 7:19 PM

# re: F# FizzBuzz
Requesting Gravatar...
let toFizzBuzz i =
match i % 3 = 0, i % 5 = 0 with
| true, true -> "FizzBuzz"
| true, _ -> "Fizz"
| _, true -> "Buzz"
| _, _ -> sprintf "%d" i
[1 .. 100] |> List.map toFizzBuzz
Left by Graham on Jun 25, 2010 7:26 PM

# re: F# FizzBuzz
Requesting Gravatar...
Vis-a-vis the recent Project Euler problem on palindromic numbers, it is interesting to note that the FizzBuzz sequence (if one begins at zero) is a palindrome:

X--F-BF--FB-F--X

(Where 'X' = FizzBuzz)
Left by TechNeilogy on Jun 25, 2010 9:00 PM

# re: F# FizzBuzz
Requesting Gravatar...
Thanks Joel, I didn't even think about the % 15... one of those moments when you just miss the obvious.
Left by MarkPearl on Jun 26, 2010 7:28 PM

# re: F# FizzBuzz
Requesting Gravatar...
TechNeilogy

lol... so true...
Left by MarkPearl on Jun 26, 2010 7:29 PM

# re: F# FizzBuzz
Requesting Gravatar...
Graham... I love you use of Match, I never realized that one could use it in that manner...

Awesome
Left by MarkPearl on Jun 26, 2010 7:30 PM

# re: F# FizzBuzz
Requesting Gravatar...
Here's a solution having some fun with active patterns:

let (|DivisibleBy|_|) d n = if n % d = 0 then Some() else None

for n in 1..100 do
match n with
| DivisibleBy 3 & DivisibleBy 5 -> "FizzBuzz"
| DivisibleBy 3 -> "Fizz"
| DivisibleBy 5 -> "Buzz"
| n -> string n
|> printfn "%s"
Left by Arjen on Jun 27, 2010 11:50 AM

Your comment:
 (will show your gravatar)


Copyright © MarkPearl | Powered by: GeeksWithBlogs.net