public
Last active

Conway's Game Of Life.

  • Download Gist
GameOfLife.hs
Haskell
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
import qualified Data.Set as S
import qualified Data.Map as M
import Control.Monad
step :: S.Set (Int, Int) -> S.Set (Int, Int)
step grid = let
neighs (i, j) = [((i + di, j + dj), 1) |
(di, dj) <- tail $ liftM2 (,) [0, -1, 1] [0, -1, 1]]
freqs = M.fromListWith (+) $ neighs =<< S.toList grid
in S.fromList [i |
(i, n) <- M.toList freqs,
(n == 3) || (n == 2 && S.member i grid)]
showGrid :: [Int] -> [Int] -> S.Set (Int, Int) -> String
showGrid w h grid =
unlines [[if S.member (i, j) grid then 'x' else ' ' | j <- w] | i <- h]
parseGrid :: [String] -> S.Set (Int, Int)
parseGrid ls = S.fromList [(i, j) |
(i, l ) <- zip [0..] ls,
(j, 'x') <- zip [0..] l]
glider = parseGrid [
" x ",
" x",
"xxx"]
main = forM_ (take 20 $ iterate step glider) $ \grid -> do
putStrLn $ showGrid [-10..10] [-10..10] grid
putStrLn $ replicate 20 '-'

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.