gpt4 book ai didi

haskell - 将 Maybe 包装在 WriterT 中以添加日志记录

转载 作者:行者123 更新时间:2023-12-02 16:09:42 25 4
gpt4 key购买 nike

我完全陷入困境,我觉得我现在可以使用一些帮助,只是为了保持理智。我想要一些简单的东西,比如向返回 Maybe 的函数添加日志记录功能,但无论我如何努力,我就是无法获得正确的类型。

这是(据我所知)我能得到的最接近的结果:

import Data.Maybe
import Control.Monad
import Control.Monad.Writer

q :: Integer -> Maybe Integer
q x = if x > 7
then Just x
else Nothing

qlog :: Integer -> WriterT [String] Maybe Integer
qlog x = do
tell ["Querying " ++ show x]
return $ q x

这仍然会导致我输入错误:

Couldn't match type ‘Maybe Integer’ with ‘Integer’
Expected type: WriterT [String] Maybe Integer
Actual type: WriterT [String] Maybe (Maybe Integer)
In a stmt of a 'do' block: return $ q x
In the expression:
do { tell ["Querying " ++ show x];
return $ q x }
In an equation for ‘qlog’:
qlog x
= do { tell ["Querying " ++ show x];
return $ q x }

我应该如何调整代码以使其编译并运行?

非常感谢您的帮助,Haskeller 同胞们!

最佳答案

为了进行类型检查,内部单子(monad)应该是 lifted :

lift :: (Monad m, MonadTrans t) => m a -> t m a

因此,您需要编写: lift $ q x; 而不是 return $ q x如:

qlog :: Integer -> WriterT [String] Maybe Integer
qlog x = do
tell ["Querying " ++ show x]
lift $ q x

关于haskell - 将 Maybe 包装在 WriterT 中以添加日志记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36246810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com