Use applicative style

This commit is contained in:
Rnhmjoj 2015-03-08 01:35:22 +01:00
parent 7b97c9c65d
commit 57120a5dae

14
life.hs
View File

@ -1,3 +1,5 @@
import Control.Applicative
import Data.List
import Matrix
type Cell = Int
@ -20,9 +22,10 @@ gprint = putStrLn . map replace . show
-- | List of neighbours cells
near :: Grid -> Pos -> [Cell]
near g (x, y) = [g ! (x+x', y+y') | x' <- [-1..1],
y' <- [-1..1],
(x',y') /= (0,0)]
near g (x, y) = map state $ neighbours \\ [(0,0)]
where
neighbours = liftA2 (,) [-1..1] [-1..1]
state (x', y') = g ! (x+x', y+y')
-- | Find if a cell will be alive in the next generation
alive :: Grid -> Pos -> Cell
@ -30,12 +33,11 @@ alive g p
| v == 0 && n == 3 = 1
| v == 1 && (n == 2 || n == 3) = 1
| otherwise = 0
where
(n, v) = (sum (near g p), g ! p)
where (n, v) = (sum (near g p), g ! p)
-- | Compute next generation
next :: Grid -> Grid
next g = fmap (alive g) (indeces g)
next g = alive g <$> indeces g
main :: IO ()
main = mapM_ gprint (iterate next grid)