Skip to content

zongwu's blog

Tag: #软件设计

WriterT 相关源码分析

看完ReaderT源码,接着来分析WriterT的源码。

示例

先看一个超级简单的例子:

import Control.Monad
import Control.Monad.Trans.Writer

data LogEntry = LogEntry { msg :: String } deriving (Eq, Show)

calc :: Writer [LogEntry] Integer calc = do tell [LogEntry "Start"] let x = sum [1 .. 10000000] tell [LogEntry (show x)] tell [LogEntry "done"] return x

test = execWriter calc test2 = runWriter calc

test执行结果:

[LogEntry {msg = "Start"},LogEntry {msg = "50000005000000"},LogEntry {msg = "done"}]