Phillip Trelford's Array

POKE 36879,255

Functional Fizz Buzz

Fizz-Buzz or Bizz Buzz is a word game, popularized by Jeff Atwood in the article:

Why Can’t Programmers… Program?

The game has been turned into a simple programming test:

Write a program that prints the numbers from 1 to 100. But for multiples of 3 print "Fizz" instead of the number and for the multiples of 5 print "Buzz". For numbers which are multiples of both 3 and 5 print "FizzBuzz".

If you’re involved in hiring programmers then the article is probably worth a read.

This kind of problem can be expressed very concisely in functional programming languages to the point where the code fits in a tweet.

Haskell

Last month Calvin Bottoms posted an article describing and implementation of Fizz-Buzz in Haskell expressed in a mere 78 characters:

[max(show x)(concat[n|(f,n)<-[(3,"Fizz"),(5,"Buzz")],mod x f==0])|x<-[1..100]]

Higher order functions and list comprehensions (a feature taken from Miranda) make this very terse, but also a little impenetrable.

F#

Rather more verbose (122 characters) but perhaps a little more readable:

for n in 1..100 do printfn "%s" <| match n%3, n%5 with 
0,0 -> "FizzBuzz" | 0,_ -> "Fizz" | _,0 -> "Buzz" | _,_ -> string n

Pattern matching makes the various states relatively obvious.

Clojure

Martin Trojer sent over this quite elegant Clojure implementation via Twitter:

(map #(cond (zero? (mod % 15)) "FizzBuzz" (zero? (mod % 3)) "Fizz" 
(zero? (mod % 5)) "Buzz" :else %) (range 1 101))

Testing for “FizzBuzz” using modulus 15 helps reduce the character count.

Erlang

I’ve been playing with Erlang recently and Fizz-Buzz is my new “Hello World” app. This was my first effort:

f(101)->ok;
f(X)->Y=case{X rem 3,X rem 5}of{0,0}->fizzbuzz;{0,_}->fizz;{_,0}->buzz;
{_,_}->X end,io:format("~w~n",[Y]),f(X+1). 

Erlang doesn’t have a for loop construct built-in so I resorted to recursion instead.

That said you can achieve the same thing using the lists module seq and foreach functions:

lists:foreach(fun(X)->io:format("~w~n",[case{X rem 3,X rem 5}of{0,0}->fizzbuzz;
{0,_}->fizz;{_,0}->buzz;{_,_}->X end])end,lists:seq(1,100)).

Next?

Is Fizz-Buzz the new “Hello World”?

I think it might be, despite Jeff’s protestations, take a peek at Fizz-Buzz on Rosetta Code.

Life in a tweet

This week I had pleasure of meeting Vagif Abilov on Tomas Petricek and I’s Advanced F# course at Skills Matter. Vagif mentioned a Ruby implementation of Conway’s Game of Life being squeezed into 140 characters for tweeting and how that might look in F#.

Here’s the 140 characters of Ruby:

life=->g,s{(0..s*s-1).map{|i|->n{n==3||(g[i]&&n==2)||nil}
[[g[i-s-1],g[i-s],g[i-s+1],g[i-1],g[i+1],g[i+s-1],g[i+s],g[i+s+1]]
.compact.count]}}

And 127 characters of F#:

let f s g = g|>List.mapi(fun i x->match Seq.sumBy(fun o->
g.[abs((i+o)%(s*s))])[-1-s;-s;1-s;-1;1;-1+s;s;1+s]with 3->1|2->x|_->0)

Like the Ruby version, the F# implementation above takes a shortcut when computing points outside of the grid.

This is what the function looks like with added white space, variable names and comments:

let generate size grid =
    grid |> List.mapi (fun i value->
        /// Neighbours count
        let count =
            let s = size
            [-1-s;-s;1-s;
             -1;     1;
             -1+s;s; 1+s]
            |> Seq.sumBy (fun o ->
                let offset = abs((i + o) % grid.Length)
                grid.[offset]
            )
        // Evaluate life
        match value, count with 
        | _, 3 -> 1
        | n, 2 -> n
        | _, _ -> 0 
    )

The  game grid can is expressed as a list:

let grid = [
    0;0;0;0;0
    0;0;1;0;0
    0;0;1;1;0
    0;0;1;0;0
    0;0;0;0;0
    ]

Visualizing the grid on the console:

let show (size:int) (grid:int list) =
    for y=0 to (grid.Length/size)-1 do
       [0..size-1] 
       |> List.map (fun x -> grid.[y * size + x].ToString())
       |> String.concat "" 
       |> printfn "%s"

Or watch it running in your browser: http://trelford.com/Life/Life.htm

(I used Pit to compile the F# code to JavaScript)

Life.fs (1.77 kb)

Skills Matter: F# Intro Talk Material - Slides & Code Samples

Thanks to everyone who made it down to Skills Matter on Tuesday for Scott Cowan's Lucene.Net talk and my F# Introduction talk. There was a great turnout, with more chairs needing to be brought in, plus some excellent questions, and also a good group for the pub after. My slides are attached to this post and a video/podcast should be available soon here:

http://skillsmatter.com/podcast/open-source-dot-net/phil-trelford-f-introduction 

I have also put the code samples from my F# Intro talk up on the F# Wiki:

  • fsweet sample WFP Twitter client script (<200 lines)
  • Mastermind sample WPF mini-game (<300 lines)

Below a screen shot of the fsweet script, showing a Twitter friends timeline, used to make a live Twitter update during the talk. 

screenshot of fsweet F# Twitter client

FSharpIntroduction.pptx (376.59 kb)

fsweet.fsx (8.58 kb)