Monday, October 8, 2012

Learning F# 3.0 : LINQ in F# (sample for FizzBuzz)

To use LINQ in F#, There is no need for creating mapper function. And there is also no need for using accumulator in reducer function. The below is the sample for FizzBuzz.
module FizzBuzzLinq =
    open System.Data
    open System.Data.Linq

    let fizzBuzz (fromNum:int) (toNum:int) =
        let fizzBuzzReducer (number:int) =
            match (number % 3, number % 5) with
            | (0, 0) -> "FizzBuzz"
            | (0, _) -> "Fizz"
            | (_, 0) -> "Buzz"
            | (_, _) -> number.ToString()
        let numberList = [ fromNum..toNum ]
        query { for number in numberList do
                select (fizzBuzzReducer number) }

(FizzBuzzLinq.fizzBuzz 1 40) |> Seq.iter (fun elem -> System.Console.WriteLine(elem))
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

module FizzBuzzLinq = begin
  val fizzBuzz : fromNum:int -> toNum:int -> seq<string>
end
val it : unit = ()

No comments:

Post a Comment