Skip to content

Instantly share code, notes, and snippets.

@Javran
Created August 23, 2014 00:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Javran/eed695b4f837cc8ea214 to your computer and use it in GitHub Desktop.
Save Javran/eed695b4f837cc8ea214 to your computer and use it in GitHub Desktop.
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