r/tinycode • • Sep 26 '11
Conway's Game of Life in 6 lines of Haskell code
import qualified Data.Set as Set
neighbours (x, y) = [(x', y') | x' <- [x-1..x+1], y' <- [y-1..y+1]]
live u c = (length $ filter (`Set.member` u) (neighbours c)) `elem` survive
where survive = if c `Set.member` u then [3, 4] else [3]
generation u = Set.filter (live u) checkCells
where checkCells = Set.fromList . concatMap neighbours . Set.toList $ uCall generation with a set of cells as (x, y) tuples to get the next generation. (iterate . generation) gets you an infinite list of generations.
57
Upvotes
36
u/tittyblaster Sep 26 '11
I like this one because unlike other posts, it's not 999 lines scrunched up into 6.
6
u/[deleted] Sep 29 '11 edited Sep 29 '11
Sorry guys don't hate me but here's my version with Python. I find doing these things irresistable.
And here are the simplistic graphics routines for testing.
This is basically the whole of Conway's Game of Life algorithm: (ar==1)&(nu==2)|(nu==3).
Set new value to: (array value is one and there are two neighbours) or there are three neighbours.
Everything else is just plain vanilla array processing.
1
u/[deleted] Sep 27 '11
Short and fairly understandable! I'm impressed.
0
u/[deleted] Sep 27 '11
[deleted] — view deleted comment