Unable to compile Writer Monad example from “Learn you a Haskell”

[亡魂溺海] 提交于 2019-12-01 03:38:08

LYAH is outdated in this example. You should use the writer smart constructor method instead of the (now non-existent) Writer data constructor.

To expand a bit, these data types were updated to be more compatible with monad transformers. As a result, there is a general WriterT, for use in a monad transformer stack, and a Writer type synonym that composes WriterT with Identity. Because of this, there is no longer a data constructor associated specifically with the Writer type (since Writer is a type synonym).

Luckily, despite this complication, the solution is pretty simple: replace Writer with writer.

The correct version in GHC 7.10.3 should be like this

import Control.Monad.Writer

logNumber :: Int -> Writer [String] Int
logNumber x = writer (x, ["Got number: " ++ show x])

multWithLog :: Writer [String] Int
multWithLog = do
    a <- logNumber 3
    b <- logNumber 5
    return (a*b)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!