Created
April 10, 2019 22:53
-
-
Save vakili/e208ec386de8bdb8e5fc180028ac0c22 to your computer and use it in GitHub Desktop.
game of life
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Life where | |
-- a cell is identified by a pair of coordinates | |
type Cell = (Int, Int) | |
-- a cell is either live or dead | |
data State = Live | Dead deriving Eq | |
-- a grid assigns a state to each cell | |
type Grid = Cell -> State | |
-- neighbours are adjacent cells | |
neighbours :: Cell -> [Cell] | |
neighbours (x,y) = [(x+i, y+j) | i <- [-1,0,1], j <- [-1,0,1], (i,j) /= (0,0)] | |
-- given a grid and a cell, some neighbours are live | |
liveNeighbours :: Grid -> Cell -> [Cell] | |
liveNeighbours grid cell = filter isLive (neighbours cell) | |
where isLive :: Cell -> Bool | |
-- the grid determines whether the cell is live or not | |
isLive cell = grid cell == Live | |
{- | |
Rules: | |
1. Any live cell with 2 or 3 neighbours lives, else it dies (by starvation or overpopulation). | |
2. Any dead cell with exactly 3 live neighbours becomes live (by reproduction). | |
-} | |
life :: Grid -> Grid | |
-- life :: (Cell -> State) -> (Cell -> State) | |
life grid cell = case grid cell of | |
Live -> if n == 2 || n == 3 then Live else Dead | |
where n = length $ liveNeighbours grid cell | |
Dead -> if n == 3 then Live else Dead | |
where n = length $ liveNeighbours grid cell |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment