在the chapter 14 of Real World Haskell (Monads)中,注入函数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
我很担心它的类型签名是什么。
答案 0 :(得分:11)
在行
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
不是字符串,对于任何Maybe a
都是a
- 因此类型错误。
您可能正在寻找
Nothing :: Maybe String -- no return here
工作正常。
顺便说一句,您可以要求GHCi使用:t
命令为表达式提供类型:
> :t return Nothing
Monad m => m (Maybe a)
答案 1 :(得分:7)
之间的区别:
*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