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

Wrapping Maybe in WriterT to add logging

我完全被困住了,我觉得我现在需要一些帮助,只是为了保持理智。我想要一些简单的东西,比如向 returns 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 }

我应该如何调整代码以使其编译和工作?

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

为了进行类型检查,内部单子应该是 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