"return Nothing" 的类型签名是什么?

what is the type signature for "return Nothing"?

the chapter 14 of Real World Haskell (Monads)中,inject函数return的类型签名是return :: a -> m a,其中m a是一个类型构造函数,所以在ghci下我可以指定一个类型return arg1 的签名,例如:

*Main> return 1 :: Maybe Integer
Just 1

*Main> return "ok" :: Maybe String
Just "ok"   

因为Nothing是类型Maybe a的值,Nothing的类型是Maybe IntegerMaybe String,所以我想我可以指定类型如下:

*Main> return Nothing :: Maybe String

但是我得到一个错误:

    Couldn't match type `Maybe a0' with `[Char]'
Expected type: String
  Actual type: Maybe a0
In the first argument of `return', namely `Nothing'
In the expression: return Nothing :: Maybe String
In an equation for `it': it = return Nothing :: Maybe String

我对它的类型签名感到困惑。

两者的区别:

*Main> return 1 :: Maybe Integer

*Main> return Nothing :: Maybe String

就是1的类型是Integer,而Nothing的类型是Maybe a。如果你想将 Nothing 包装成另一个 Maybe 值,你应该像这样指定 Nothing 的类型:

*Main> return Nothing :: Maybe (Maybe String)
Just Nothing

行中

return 1
return "ok"

returnMaybe monad 中工作,所以 return = Just 在这里。

行中

return Nothing :: Maybe String

编译器发现您的代码具有以下形式

return ... :: Maybe ...

所以,再一次,return = Just。你的代码相当于

Just Nothing :: Maybe String

相同
Just (Nothing :: String)

Nothing 不是字符串,它是任何 aMaybe a -- 因此类型错误。

您可能正在寻找

Nothing :: Maybe String -- no return here

效果很好。

顺便说一句,您可以使用 :t 命令要求 GHCi 给出表达式的类型:

> :t return Nothing
Monad m => m (Maybe a)