"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 Integer
或Maybe 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"
return
在 Maybe
monad 中工作,所以 return = Just
在这里。
行中
return Nothing :: Maybe String
编译器发现您的代码具有以下形式
return ... :: Maybe ...
所以,再一次,return = Just
。你的代码相当于
Just Nothing :: Maybe String
与
相同
Just (Nothing :: String)
但 Nothing
不是字符串,它是任何 a
的 Maybe a
-- 因此类型错误。
您可能正在寻找
Nothing :: Maybe String -- no return here
效果很好。
顺便说一句,您可以使用 :t
命令要求 GHCi 给出表达式的类型:
> :t return Nothing
Monad m => m (Maybe a)
在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 Integer
或Maybe 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"
return
在 Maybe
monad 中工作,所以 return = Just
在这里。
行中
return Nothing :: Maybe String
编译器发现您的代码具有以下形式
return ... :: Maybe ...
所以,再一次,return = Just
。你的代码相当于
Just Nothing :: Maybe String
与
相同Just (Nothing :: String)
但 Nothing
不是字符串,它是任何 a
的 Maybe a
-- 因此类型错误。
您可能正在寻找
Nothing :: Maybe String -- no return here
效果很好。
顺便说一句,您可以使用 :t
命令要求 GHCi 给出表达式的类型:
> :t return Nothing
Monad m => m (Maybe a)