-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGame_of_life.fold
53 lines (36 loc) · 1.25 KB
/
Game_of_life.fold
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
-- http://rhnh.net/2012/01/02/conway's-game-of-life-in-haskell
load Control.Monad only: replicate
load System.Random
load World only: (World, Loc)
load World as: W
-- Generic utility functions
def count :: {Eq a} -> a -> List a -> Int
def count x xs =
#(filter (x ==) xs)
-- Game of Life
@deriving (Eq, Show)
type Cell = Alive | Dead
def random_cell :: IO Cell =
let x = random_io in
if x then Alive else Dead
def random_world :: Int -> Int -> IO (World Cell_State)
def random_world width height =
let states = replicate (width * height) random_cell,
bounds = ((0, 0), (width - 1, height - 1))
W.from_list bounds W.Torus states
def neighbors_alive :: World CellState -> Loc -> Int
def neighbors_alive w x =
count Alive neighbor_states
where
neighbor_states = map cell_at (neighbors x),
neighbors = W.neighbors W.moore_neighbors w,
cell_at = W.cell_at w
def transition :: Cell -> Int -> Cell
def transition Deadn n if (n == 3) = Alive
| transition Alive n if (n == 2) || (n == 3) = Alive
| transition _ _ = Dead
def evolve_cell :: World CellState -> Loc -> CellState -> CellState
def evolve_cell w x s = transition s (neighbors_alive w x)
def render_cell :: CellState -> Char
def render_cell Alive = '@'
| render_cell Dead = ' '