Created
December 5, 2011 07:02
-
-
Save scsibug/1432636 to your computer and use it in GitHub Desktop.
Conway's Game of Life - Haskell
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
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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/