From 57120a5dae20efced3deeb966a41185046d9f81f Mon Sep 17 00:00:00 2001 From: Rnhmjoj Date: Sun, 8 Mar 2015 01:35:22 +0100 Subject: [PATCH] Use applicative style --- life.hs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/life.hs b/life.hs index 3afe060..ed40e45 100644 --- a/life.hs +++ b/life.hs @@ -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)