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

标签 haskell monads instances

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

相关文章:

haskell - 类型族、GADT 和命名记录的编译错误

c# - 为什么在即将到来的 .NET 4.0 中没有像 IMonad<T> 这样的东西

list - 如何在 Haskell 列表中移动元素?

plugins - 帮助 Haskell 动态插件加载

haskell - 处理 IO 操作

Python:对列表中的类实例求和

java - 在java中将类的实例存储在另一个类中

java - 从其他类控制 JComponent

parsing - 在guards haskell中使用case表达式时解析错误

scala - 在聚合 monad 上实现 flatMap