2026-09-25
Replay.hs
data Event = Deposit Int | Withdraw Int
deriving Show
replay :: Int -> [Event] -> Either String Int
残高startから始めてイベント列を古い順に適用し、最後の残高をRightで返すreplayを書いてください。Deposit nはnを足し、Withdraw nはnを引きます。ただしnがその時点の残高を超える出金が来たら、そこで止めてLeft "event i: … exceeds balance b"を返します(iは1から数えた位置、…はshowしたイベント、bはその時点の残高)。イベントが空ならRight startです。replay 0 [Deposit 50, Withdraw 20] → Right 30、replay 0 [Deposit 10, Withdraw 20, Deposit 100] → Left "event 2: Withdraw 20 exceeds balance 10"、replay 5 [] → Right 5
Reference
import Control.Monad (foldM)
import Control.Monad (foldM)
replay :: Int -> [Event] -> Either String Int
replay start events = foldM step start (zip [1 :: Int ..] events)
where
step bal (_, Deposit n) = Right (bal + n)
step bal (i, e@(Withdraw n))
| n > bal = Left ("event " ++ show i ++ ": " ++ show e ++ " exceeds balance " ++ show bal)
| otherwise = Right (bal - n)
状態を1つずつ更新していく再生は畳み込みですが、途中で失敗したら止まりたいので、foldlではなくControl.MonadのfoldMをEither Stringモナドの中で使います。stepがLeftを返した時点で>>=がそれ以降を捨てるので、残りのイベントは見られもしません(replay 0 [Withdraw 1, undefined]もLeftを返して止まります)。stepが成功すればRightの中身が次の残高として渡るので、畳み込みの形はfoldlと変わりません。位置はzip [1 :: Int ..] eventsで各イベントに添えます。:: Intが無いと、[1 ..]の型がshowとEnumだけからは決まらず、-Wallで既定の型への defaulting が警告されます。e@(Withdraw n)のasパターンで、分解したnと、メッセージに出すイベント全体の両方を手元に置いています。これは参考実装であり、唯一の正解ではありません。明示的な再帰で書いても、eitherで分岐しながらfoldlで書いても同じ結果になります。