Skip to content

Instantly share code, notes, and snippets.

@AndrasKovacs
Last active December 17, 2015 09:59
Show Gist options
  • Save AndrasKovacs/5591393 to your computer and use it in GitHub Desktop.
Save AndrasKovacs/5591393 to your computer and use it in GitHub Desktop.
Conway's Game Of Life.
import qualified Data.Set as S
import qualified Data.Map as M
import Control.Monad
import Data.Bool
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 [[bool ' ' 'x' (S.member (i, j) grid) | 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 '-'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment