Skip to content

Instantly share code, notes, and snippets.

@scsibug
Created December 5, 2011 07:02
Show Gist options
  • Save scsibug/1432636 to your computer and use it in GitHub Desktop.
Save scsibug/1432636 to your computer and use it in GitHub Desktop.
Conway's Game of Life - Haskell
import Data.Set
import Prelude hiding (map, filter)
generation g = filter (\p -> or [liveRule p g, spawnRule p g]) (candidates g)
liveRule p g = (member p g) && ((neighborCount p g) `elem` [2,3])
spawnRule p g = not(member p g) && ((neighborCount p g) == 3)
neighborCount p g = size $ intersection (border p) g
candidates g = union g (foldl union empty (toList (map border g)))
border (x,y) = fromList [(a+x,b+y) | a <- [-1..1], b <- [-1..1], (a,b) /= (0,0)]
------------------------------------------------------------------------------
-- Example of using this with a glider:
glider = fromList [(0,0),(0,1),(0,2),(-1,0),(-2,1)]
-- 20 generations
runGlider = take 20 (iterate generation glider)
@scsibug
Copy link
Author

scsibug commented Dec 5, 2011

After writing this, I've found someone has written something similar in just 6 lines: http://www.reddit.com/r/tinycode/comments/ks7y5/conways_game_of_life_in_6_lines_of_haskell_code/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment