You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 07:55:29