Haskell中如何调用自定义Monad实例?
自定义Monad实例的调用疑问
我正在初步学习Monad,已经理解了Maybe Monad的用法,比如在GHCi中的调用示例:
ghci> return "WHAT" :: Maybe String Just "WHAT" ghci> Just 9 >>= \x -> return (x*10) Just 90 ghci> Nothing >>= \x -> return (x*10) Nothing
但我自己定义了如下自定义类型的Monad实例:
newtype CustomM a = CustomM {runCustomM:: a -> String} instance Monad CustomM where return a = CustomM (\a -> mempty) m >>= f = CustomM (\a -> mempty) instance Functor CustomM where fmap = liftM instance Applicative CustomM where pure = return; (<*>) = ap
现在有两个疑问:
- 该如何调用自己的CustomM Monad实例,而不是默认的Maybe Monad?
- 我怀疑使用
return会调用Maybe Monad的实现,另外>>=需要特定类型,这该如何处理?
注:我暂时让bind与return的实现一致,因为我仍不清楚它应该返回什么,以及如何在左侧未明确指定包装类型的情况下,对Monad m中的值a调用函数f,这部分我会另开帖子提问。
内容的提问来源于stack exchange,提问作者Piskator
相关产品推荐
相关产品推荐

