標準Control.Monad.Writer.censor
是雙重的標準 Control.Monad.Reader.local
,與censor
修改寫入器狀態 計算和local
後修改所述讀取器狀態 之前計算:如何編寫這個更通用的`Control.Monad.Writer.censor`版本?
censor :: (w -> w) -> Writer w a -> Writer w a
local :: (r -> r) -> Reader r a -> Reader r a
然而,Reader
和Writer
monads並非完全對稱的 。也就是說,一個寫作者計算產生了結果, 除了寫作者狀態,並且我試圖編寫版本的censor
利用這種不對稱性。我想 編寫一個函數
censorWithResult :: (a -> w -> w) -> Writer w a -> Writer w a
這需要,除了向筆者狀態下接收計算的 結果a -> w -> w
類型的變壓器。我不用 瞭解如何使用tell
,listen
和pass
來編寫此功能。
精確的行爲我期待的是,如果
ma :: Writer w a
f :: a -> w -> w
和
runWriter ma = (r , y)
然後
runWriter (censorWithResult f ma) = (r , f r y)
而
runWriter (censor g ma) = (r , g y)
當g :: w -> w
。
例
這不應該是必要了解的問題,但這裏的激勵例子的 簡化版本:
import Control.Applicative
import Control.Monad.Writer
-- Call-trace data type for functions from 'Int' to 'Int'.
--
-- A 'Call x subs r' is for a call with argument 'x', sub calls
-- 'subs', and result 'r'.
data Trace = Call Int Forest Int
type Forest = [Trace]
-- A writer monad for capturing call traces.
type M a = Writer Forest a
-- Recursive traced negation function.
--
-- E.g. we expect that
--
-- runWriter (t 2) = (-2 , Call 2 [Call 1 [Call 0 [] 0] -1] -2)
t , n :: Int -> M Int
t x = trace n x
n x = if x <= 0 then pure 0 else subtract 1 <$> t (x - 1)
trace :: (Int -> M Int) -> (Int -> M Int)
trace h x = do
censorWithResult (\r subs -> [Call x subs r]) (h x)
-- The idea is that if 'ma :: Writer w a' and 'runWriter ma = (r , y)'
-- then 'runWriter (censorWithResult f ma) = (r , f r y)'. I.e.,
-- 'censorWithResult' is like 'Control.Monad.Writer.censor', except it
-- has access to the result of the 'Writer' computation, in addition
-- to the written data.
censorWithResult :: (a -> w -> w) -> Writer w a -> Writer w a
censorWithResult = undefined
在monad外面思考的方法:D – ntc2