gpt4 book ai didi

haskell - 函数类型的 Applicative 和 Monad 实例?

转载 作者:行者123 更新时间:2023-12-02 00:50:40 25 4
gpt4 key购买 nike

我有一个类似于下面的 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/

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