aoc2025

Advent of Code 2025
git clone git://git.rr3.xyz/aoc2025
Log | Files | Refs | Submodules

Cellular.hs (750B)


      1 module Common.Cellular (Cellular, neighbor, self, step, stabilize) where
      2 
      3 import Common.Matrix (Matrix)
      4 import Common.Matrix qualified as M
      5 import Common.Util (untilFixed)
      6 import Control.Monad.Reader
      7 import Data.Maybe (fromJust)
      8 
      9 newtype Cellular s a = Cellular (Reader (Matrix s, Int, Int) a)
     10     deriving (Functor, Applicative, Monad)
     11 
     12 neighbor :: (Int, Int) -> Cellular s (Maybe s)
     13 neighbor (di, dj) = Cellular $ asks \(m, i, j) -> m M.!? (i + di, j + dj)
     14 
     15 self :: Cellular s s
     16 self = fromJust <$> neighbor (0, 0)
     17 
     18 step :: Cellular s s -> Matrix s -> Matrix s
     19 step (Cellular c) m = M.generate (M.nrows m) (M.ncols m) \(i, j) -> c `runReader` (m, i, j)
     20 
     21 stabilize :: (Eq s) => Cellular s s -> Matrix s -> Matrix s
     22 stabilize c = untilFixed (step c)