-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Andrew Mason
committed
May 7, 2016
1 parent
294d33e
commit a74a11a
Showing
1 changed file
with
42 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
import Control.Monad | ||
import Data.Matrix | ||
|
||
type Cell = Bool | ||
|
||
next :: Cell -> [Cell] -> Cell | ||
next True cs | ||
| neighbors < 2 = False | ||
| neighbors == 2 || neighbors == 3 = True | ||
| otherwise = False | ||
where neighbors = neighborCount cs | ||
next False cs | ||
| neighborCount cs == 3 = True | ||
| otherwise = False | ||
|
||
neighborCount :: ([Cell] -> Int) | ||
neighborCount = length . filter id | ||
|
||
step :: Matrix Cell -> Matrix Cell | ||
step world = | ||
foldl (\w r -> mapRow (\c cell -> next cell (neighborsOf r c)) r w) world [1..rmax] | ||
where rmax = nrows world | ||
cmax = ncols world | ||
allNeighborCoords r c = [ (r + r', c + c') | r' <- [-1..1], c' <- [-1..1] ] | ||
neighborCoordsOf r c = [ coord | coord <- allNeighborCoords r c, (okCoord coord r c) ] | ||
neighborsOf r c = map (\(x, y) -> getElem x y world) $ neighborCoordsOf r c | ||
okCoord (x, y) r c | ||
| x == r && y == c = False | ||
| x < 1 || x > rmax = False | ||
| y < 1 || y > cmax = False | ||
| otherwise = True | ||
|
||
convert :: (a -> b) -> Matrix a -> Matrix b | ||
convert f m = fromList (nrows m) (ncols m) $ map f $ toList m | ||
|
||
drawAndStep world = do | ||
print $ convert (\x -> if x then '.' else '_') world | ||
return $ step world | ||
|
||
main = do foldM (\w _ -> drawAndStep w) initialWorld iterations | ||
where initialWorld = fromList 9 9 $ cycle [True, True, False, True] | ||
iterations = [1..] |