Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Comonad, Zipper and Conway's Game of Life (Part 2) - First Solution
import Data.List
-- worlds are represented by lists
type World a = [a]
waveRule :: Char -> Char -> Char -> Char
waveRule _ l r
| fromL && fromR = 'X' -- wave from both dir
| fromL = '>' -- from l only
| fromR = '<' -- from r only
| otherwise = ' ' -- nothing
where
fromL = l `elem` ">*X"
fromR = r `elem` "<*X"
nextGen :: World Char -> World Char
-- the resulting world must be of the same length
nextGen world = take (length world)
-- take 3 elements, Left, Current, Right in order
-- and apply the rule
. map (\ (l:c:r:_) -> waveRule c l r)
-- for each cell there's a correponding list
-- from which the first 3 elements can be taken
$ tails world'
where
-- pad the world with spaces
-- so we can be sure that every cell can grab
-- its neighboring cell states
world' = " " ++ world ++ " "
main :: IO ()
main = mapM_ putStrLn (take 20 (iterate nextGen startStr))
where startStr = "* > * * < **<"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment