如何使用Monad.Writer进行跟踪?

时间:2016-10-02 17:07:32

标签: haskell monads tracing

我的代码如下所示:

我想在tokenize函数中使用tell来写入同一个Writer Monad。这可能吗?

tokenize :: T.Text -> T.Text -> [Token]
tokenize t token
   | T.null t = addToken token []
   | h == ' ' = addToken token (tokenize r "")
   | h == '"' = let (t', r') = consumeString r
                in addToken t' (tokenize r' "")
   | otherwise = tokenize r (T.snoc token h)
   where h = T.head t
         r = T.tail t

parse :: [T.Text] -> W.Writer String [Token]
parse lines = do
    let x = concatMap (\l -> tokenize l "") lines
    W.tell "hello"
    return x

main :: IO ()
main = do
    content <- readContent
    let lines = toTextList content
    let (res, log) = W.runWriter $ parse lines
    forM_ res $ \x ->
        print x
    print log

1 个答案:

答案 0 :(得分:1)

您只需将grades = 'B' 'B' 'F' 'A' 'A' 'D' 的结果提升到tokenize

即可
Writer

然后tokenize :: T.Text -> T.Text -> W.Writer [Token] tokenize t token | T.null t = return $ addToken token [] | h == ' ' = return $ addToken token (tokenize r "") | h == '"' = let (t', r') = consumeString r in return $ addToken t' (tokenize r' "") | otherwise = return $ tokenize r (T.snoc token h) where h = T.head t r = T.tail t 必须更改以处理来自parse的monadic结果:

tokenize