我有一個函數鏈接狀態單子
step :: Int -> State Int Int
step n = get >>= \x -> put (x `div` n) >> return (x `mod` n)
λ> runState (step 25) 41
(16,1)
如何運行的step
個序列,與n
不同的值,並使用來自最後一步的狀態下每一步?
所以示例中的步驟將是如下
一步一個產生(16,1)
然後我想用作輸入我與n = 10
下一步應該產生(6, 2)
。第一步添加1,第一步添加16,新建n。
n = 25 gives (16,1) then
n = 10 gives (6,2) then
n = 5 gives (1,3) then
n = 1 gives (0,4)
我知道在這裏使用State
可能不正確;但我試圖用它來學習。
可能的目標是與狀態monad一起實現此功能。
greedy :: Double -> Int
greedy owed = snd $ foldl go (pennies,0) [25, 10, 5, 1]
where
pennies = floor . (*100) $ owed
go (remaining,counter) coin = (remaining',counter')
where
remaining' = remaining `mod` coin
counter' = counter + remaining `div` coin
你說的是不是'一步其他任何1 >>第2步>>第3步? – Cubic
@Cubic,我修改了我的問題。 – matthias