Use applicative style
This commit is contained in:
parent
7b97c9c65d
commit
57120a5dae
14
life.hs
14
life.hs
@ -1,3 +1,5 @@
|
|||||||
|
import Control.Applicative
|
||||||
|
import Data.List
|
||||||
import Matrix
|
import Matrix
|
||||||
|
|
||||||
type Cell = Int
|
type Cell = Int
|
||||||
@ -20,9 +22,10 @@ gprint = putStrLn . map replace . show
|
|||||||
|
|
||||||
-- | List of neighbours cells
|
-- | List of neighbours cells
|
||||||
near :: Grid -> Pos -> [Cell]
|
near :: Grid -> Pos -> [Cell]
|
||||||
near g (x, y) = [g ! (x+x', y+y') | x' <- [-1..1],
|
near g (x, y) = map state $ neighbours \\ [(0,0)]
|
||||||
y' <- [-1..1],
|
where
|
||||||
(x',y') /= (0,0)]
|
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
|
-- | Find if a cell will be alive in the next generation
|
||||||
alive :: Grid -> Pos -> Cell
|
alive :: Grid -> Pos -> Cell
|
||||||
@ -30,12 +33,11 @@ alive g p
|
|||||||
| v == 0 && n == 3 = 1
|
| v == 0 && n == 3 = 1
|
||||||
| v == 1 && (n == 2 || n == 3) = 1
|
| v == 1 && (n == 2 || n == 3) = 1
|
||||||
| otherwise = 0
|
| otherwise = 0
|
||||||
where
|
where (n, v) = (sum (near g p), g ! p)
|
||||||
(n, v) = (sum (near g p), g ! p)
|
|
||||||
|
|
||||||
-- | Compute next generation
|
-- | Compute next generation
|
||||||
next :: Grid -> Grid
|
next :: Grid -> Grid
|
||||||
next g = fmap (alive g) (indeces g)
|
next g = alive g <$> indeces g
|
||||||
|
|
||||||
main :: IO ()
|
main :: IO ()
|
||||||
main = mapM_ gprint (iterate next grid)
|
main = mapM_ gprint (iterate next grid)
|
||||||
|
Loading…
Reference in New Issue
Block a user