Phillip Trelford's Array

POKE 36879,255

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:


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;     1;
             -1+s;s; 1+s]
            |> Seq.sumBy (fun o ->
                let offset = abs((i + o) % grid.Length)
        // Evaluate life
        match value, count with 
        | _, 3 -> 1
        | n, 2 -> n
        | _, _ -> 0 

The  game grid can is expressed as a list:

let grid = [

Visualizing the grid on the console:

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

Or watch it running in your browser:

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

Life.fs (1.77 kb)

Comments (1) -

  • Andrew Pennebaker

    3/8/2013 4:29:34 PM |

    Here's a Brainfuck interpreter in C, in a bit over a tweet. Brainfuck is trivially turing-complete; implementing the game of life in Brainfuck is left as an exercise for the reader.

    char m[9999],*n[99],*r=m,*p=m+5000,**s=n,d,c;main(){for(read(0,r,4000);c=*r;

Pingbacks and trackbacks (3)+

Comments are closed