haskell - 为什么 "return Nothing"什么都不返回?

标签 haskell monads maybe

"return a"应该在一些 Monad 的上下文中包装 a:

*Main> :i return
class Applicative m => Monad (m :: * -> *) where
  ...
  return :: a -> m a
  ...
        -- Defined in ‘GHC.Base’

如果我问 GHCI “return Nothing”的类型是什么,它符合:
*Main> :t return Nothing
return Nothing :: Monad m => m (Maybe a)

但是如果我评估它,我看不到外部 Monad,只有内部的 Maybe:
*Main>  return Nothing
Nothing

最佳答案

当 GHCi 去打印一个值时,它会尝试两种不同的事情。首先,它尝试将类型与 IO a 统一起来。对于一些 a .如果它可以做到这一点,那么它会执行 IO 操作并尝试打印结果。如果它不能这样做,它会尝试打印给定的值。在您的情况下,Monad m => m (Maybe a)可与IO (Maybe a) 统一.

查看此 GHCi session 可能会有所帮助:

Prelude> return Nothing
Nothing
Prelude> return Nothing :: IO (Maybe a)
Nothing
Prelude> return Nothing :: Maybe (Maybe a)
Just Nothing
Prelude> Nothing
Nothing

关于haskell - 为什么 "return Nothing"什么都不返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45558914/

相关文章:

monads - 为什么验证会违反 monad 法则?

clojure - 这个 do-monad 可以用 let block 代替吗?

haskell - 也许 monad 绑定(bind)函数优先级

Haskell:将 Bool 视为 Int

haskell - 柯里化(Currying)函数的实际使用?

haskell - 计算结构(Monad、Arrows 等)

list - 为什么我要使用 Maybe 而不是 List?

haskell - 错误处理和单子(monad)?

haskell - 我可以在 GHCi 中添加实例声明吗

haskell - 使用 cmdargs 排序参数