如何使用 syb mkM

How to use syb mkM

我刚刚发现了 syb 库的强大功能并试图找出它的局限性。

我已经 everywhere 工作了:

> :set -XDeriveDataTypeable
> :set -XGeneralizedNewtypeDeriving
> import Data.Generics
> newtype MyInt = MyInt Int deriving (Show, Eq, Num, Ord, Data)
> incMyInt (MyInt i) = MyInt $ 1 + i
> printMyInt (MyInt i) = putStrLn $ "MyInt = " ++ show i
> :t mkT incMyInt
mkT incMyInt :: Typeable a => a -> a

> :t mkM printMyInt

<interactive>:1:5: error:
    • Couldn't match type ‘()’ with ‘MyInt’
      Expected type: () -> IO ()
        Actual type: MyInt -> IO ()

mkT 和 mkM 看起来很相似,我不明白为什么 mkM 不能用于 printMyInt

> :t mkM
mkM :: (Monad m, Typeable a, Typeable b) => (b -> m b) -> a -> m a
> :t mkT
mkT :: (Typeable a, Typeable b) => (b -> b) -> a -> a

甚至pure

:t mkM pure

<interactive>:1:1: error:
    • Could not deduce (Typeable b0) arising from a use of ‘mkM’
      from the context: (Monad m, Typeable a)
        bound by the inferred type of
                   it :: (Monad m, Typeable a) => a -> m a
        at <interactive>:1:1

ghc 8.10.7 和 syb 0.7.2.1

printMyInt 的类型为 MyInt -> IO ().

mkM 需要 b -> m b.

类型的参数

不匹配,因为 MyInt 不是 ()

你可以写

mkM (\x -> printMyInt x >> pure x)

mkM pure 是模棱两可的。 mkM :: (Typeable a, Typeable b) => (b -> m b) -> a -> m a有两个类型参数,abbmkM pure中未确定。如果不约束b是没有问题的,但是这里有一个Typeable b的约束,不修复b.

是解决不了的