3 people like it.

functional fizz buzz

Recently witnessed a C# programmer struggle with the fizz buzz interview question. But it is straightforward in F# using pattern matching on the two-factor decision table.

1: 
2: 
3: 
4: 
5: 
6: 
7: 
8: 
9: 
let fizzbuzz n = 
    let divisible x = (n % x) = 0
    match divisible 3,divisible 5 with
        | true,false -> "fizz"
        | false,true -> "buzz"
        | true,true -> "fizzbuzz"
        | false,false -> sprintf "%d" n

[1..15] |> List.map fizzbuzz
val fizzbuzz : n:int -> string

Full name: Script.fizzbuzz
val n : int
val divisible : (int -> bool)
val x : int
val sprintf : format:Printf.StringFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.sprintf
Multiple items
module List

from Microsoft.FSharp.Collections

--------------------
type List<'T> =
  | ( [] )
  | ( :: ) of Head: 'T * Tail: 'T list
  interface IEnumerable
  interface IEnumerable<'T>
  member Head : 'T
  member IsEmpty : bool
  member Item : index:int -> 'T with get
  member Length : int
  member Tail : 'T list
  static member Cons : head:'T * tail:'T list -> 'T list
  static member Empty : 'T list

Full name: Microsoft.FSharp.Collections.List<_>
val map : mapping:('T -> 'U) -> list:'T list -> 'U list

Full name: Microsoft.FSharp.Collections.List.map
Next Version Raw view Test code New version

More information

Link:http://fssnip.net/lL
Posted:10 years ago
Author:Alan Wostenberg
Tags: puzzles