“return a”应该在某些Monad的上下文中包装a:

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

如果我问GHCI,“不归还”的类型是什么,它符合以下条件:
*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/

10-12 13:05