-
-
Save Javran/eed695b4f837cc8ea214 to your computer and use it in GitHub Desktop.
Comonad, Zipper and Conway's Game of Life (Part 2) - First Solution
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 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