Game of Life in Elm (Pt 1)

I stay as far away as possible from the front end, and have no interest in React or Angular; but Elm has piqued my interest, as a new functional language “compiled” to JavaScript. I thought it might be interesting to try and implement Conway’s Game of Life.

In this, the first part of X, I will simply render the grid. You can follow along with the repo here, and see the working final version here. I’m using Elm 0.18, the latest version at the time.

We start with the standard program for the Elm architecture:

main: Program Never Model Msg
main =
    Html.program {
        init = init,
        view = view,
        update = update,
        subscriptions = \_ -> Sub.none
    }

The simplest way to represent the grid is as a list of lists:

type Cell = Dead | Alive
type alias Row = List Cell
type alias Board = List Row
type alias Model = Board

init : (Model, Cmd Msg)
init =
    (emptyBoard, Cmd.none)

emptyBoard : Board
emptyBoard = [
        [ Dead, Dead, Dead ],
        [ Dead, Dead, Dead ],
        [ Dead, Dead, Dead ]
    ]

We need an update function:

type Msg =
    Tick

update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
    case msg of
        Tick ->
            (model, Cmd.none)

but this message will never be received, right now. Finally, we render the model as a table:

view : Model -> Html Msg
view model =
    div [] [
        h1 [] [ text "Game Of Life" ],
        div [ class "board" ] [
            table [ style [ ("border-collapse", "collapse"), ("border", "1px solid black") ] ] [
                tbody [] (List.map renderRow model)
            ]
        ]
    ]

renderRow : Row -> Html Msg
renderRow row =
    tr [] (List.map renderCell row)

renderCell : Cell -> Html Msg
renderCell box =
    td [ style [ ("border", "1px solid black"), ("height", "50px"), ("width", "50px") ] ] []

You can compile the main file using elm-make, or run elm-reactor, and you should see a 3×3 grid rendered.

In Part 2 we’ll look at how to make the “seed” more interesting.

Advertisements

One thought on “Game of Life in Elm (Pt 1)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s