我有一个类似于下面的 Blah
的数据类型,但由于该类型的一个怪癖,我无法自动派生 Functor、Applicative 和 Monad。所以我必须手动完成,但我不确定如何。我试图从 ((->) a)
的实例中获取灵感,但我不太明白 Monad 实例。
newtype Blah a = Blah (String -> a) -- deriving (Functor, Applicative, Monad)
-- this seems right
instance Functor Blah where
fmap f (Blah g) = Blah (f . g)
instance Applicative Blah where
pure = Blah . const
-- This is right, right?
(<*>) (Blah f) (Blah g) = Blah $ \x -> f x (g x)
instance Monad Blah where
return = pure
-- I'm not having any luck here.
(>>=) a b = Blah $ \c -> _
编辑:有人将此标记为另一个的副本,但我不知道从哪里可以得到答案。新型包装器使这变得困难。在我写这个问题之前,我在 (->) a
的基础中查找了 Monad
实例,但这里答案中的体操是我需要的。
最佳答案
怎么样
Blah f >>= g = Blah $ \s ->
let Blah h = g $ f s in h s
关于haskell - 函数类型的 Applicative 和 Monad 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40265999/