我正在尝试解决 Haskell 中的整个 Advent of Code 系列。
我在解决2015/06 练习时遇到了内存问题,其中有一堆指令可以打开、关闭和切换网格上的灯。目标是计算最后点亮的灯的数量。
给定指令被解析并存储在一个Instruction
类型中,这是类型定义:
data Instruction = Instruction Op Range deriving Show
data Op = Off | On | Toggle | Nop deriving Show
data Range = Range Start End deriving Show
type Start = Point
type End = Start
data Point = Point Int Int deriving Show
这是计算结果的代码。我试图通过使用类型类来抽象出灯光是布尔值的事实
gridWidth, gridHeight :: Int
gridWidth = 1000
gridHeight = 1000
initialGrid :: Togglable a => Matrix a
initialGrid = matrix gridWidth gridHeight (const initialState)
instance Monoid Op where
mempty = Nop
instance Semigroup Op where
_ <> On = On
_ <> Off = Off
x <> Nop = x
Off <> Toggle = On
On <> Toggle = Off
Toggle <> Toggle = Nop
Nop <> Toggle = Toggle
class Togglable a where
initialState :: a
apply :: Op -> a -> a
instance Togglable Bool where
initialState = False
apply On = const True
apply Off = const False
apply Toggle = not
apply Nop = id
-- Does the Range of the instruction apply to this matrix coordinate?
(<?) :: Range -> (Int, Int) -> Bool
(<?) (Range start end) (x, y) = let
(Point x1 y1) = start
(Point x2 y2) = end
(mx, my) = (x-1, y-1) -- translate from matrix coords (they start from 1!)
in and [
mx >= min x1 x2, mx <= max x1 x2,
my >= min y1 y2, my <= max y1 y2
]
stepGenerator :: Instruction -> Matrix Op
stepGenerator (Instruction op r) = let
g coord = if r <? coord then op else Nop
in matrix gridWidth gridHeight g
allStepsMatrix :: [Instruction] -> Matrix Op
allStepsMatrix = mconcat.map stepGenerator
finalGrid :: Togglable a => Matrix a -> Matrix Op -> Matrix a
finalGrid z op = fmap apply op <*> z
countOn :: Matrix Bool -> Integer
countOn = toInteger.foldr (\x -> if x then (+1) else id) 0
partA :: Challenge (String -> Integer)
partA = Challenge $ countOn.finalGrid initialGrid.allStepsMatrix.parse
解决方案将是由 inside 返回的整数partA
。parse
工作并且有类型parse :: String -> [Instruction]
代码编译并使用小矩阵(例如 10x10)运行,一旦我转向1000 gridWidth
,gridHeight
我就会遇到out of memory
错误,显然是从allStepsMatrix
函数生成的。
这里有什么可能出错的提示吗?完整代码在 GitHub 上