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

Related Posts on Geeks With Blogs
Matching Categories

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".

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.

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:

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"

match i % 3 = 0, i % 5 = 0 with

| true, true -> "FizzBuzz"

| true, _ -> "Fizz"

| _, true -> "Buzz"

| _, _ -> sprintf "%d" i

[1 .. 100] |> List.map toFizzBuzz

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

(Where 'X' = FizzBuzz)

lol... so true...

Awesome

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"