Last active
December 17, 2015 09:59
-
-
Save AndrasKovacs/5591393 to your computer and use it in GitHub Desktop.
Conway's Game Of Life.
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 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