什么是&#34的类型签名;什么都不返回"?

时间:2015-01-05 10:19:31

标签: haskell monads

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"   

由于NothingMaybe 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

我很担心它的类型签名是什么。

2 个答案:

答案 0 :(得分:11)

在行

return 1
return "ok"

returnMaybe 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的类型是IntegerNothing的类型是Maybe a吗?如果要将Nothing包装到另一个Maybe值中,则应指定Nothing的类型,如下所示:

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