# John Conway's game of life in Haskell: Code Review

I have written a small code that simulates the Game of Life by John Conway. This is the code

```
import Control.Concurrent
import System.Random
import Control.Monad
data Cell = Alive | Dead deriving Eq
instance Show Cell where
show Alive = "X"
show Dead = "0"
toCells :: [Int] -> [Cell]
toCells arr = (\ x -> if x==1 then Alive else Dead) <$> arr
getValue :: [Cell] -> Int -> Int -> Int -> Int -> Int
getValue state w h x y =
if x>=0 && x < w && y>=0 && y<h
then case state !! (y*w + x) of
Dead -> 0
Alive -> 1
else 0
countNeighbours :: [Cell] -> Int -> Int -> Int -> Int -> Int
countNeighbours state w h x y = sum $ (uncurry $ getValue state w h) <$> [(x,y+1),(x,y-1),(x+1,y+1),(x+1,y),(x+1,y-1),(x-1,y+1),(x-1,y),(x-1,y-1)]
newCell :: [Cell] -> Int -> Int -> Int -> Int -> Cell
newCell state w h x y =
if state !! (y*w + x) == Alive
then if countNeighbours state w h x y == 3 || countNeighbours state w h x y == 2 then Alive else Dead
else
if countNeighbours state w h x y == 3 then Alive else Dead
clock :: [Cell] -> Int -> Int ->Int -> Int -> [Cell]
clock state x y w h =
if x == w-1
then if y == h-1 then [newCell state w h x y] else [newCell state w h x y] ++ clock state 0 (y+1) w h
else [newCell state w h x y] ++ clock state (x+1) y w h
coolPrint :: [Cell] -> Int -> String
coolPrint [] w = "----------------"
coolPrint arr w = (show $ take w arr) ++ "\n" ++ coolPrint (drop w arr) w
update state w h= do
threadDelay 1000000
putStr "\ESC[2J"
putStrLn $ coolPrint state w
update (clock state 0 0 w h) w h
input = replicateM 625 (randomRIO (0,1))
runGame = do
s <- input
update (toCells s) 25 25
```

I have to admit, I am not very proud of it... Perhaps the update and clock functions could be implemented using the StateT monad, giving it a cleaner look. The cell data seems redundant and useless. What do you think? Any suggestion?