【问题标题】:what is the type signature for "return Nothing"?“return Nothing”的类型签名是什么?
【发布时间】:2015-01-05 10:19:30
【问题描述】:

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 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

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

【问题讨论】:

  • 通常你不需要return,在一个do块的末尾Nothing就足够了。我的意思是do Nothing 是有效的。
  • 您可能正在寻找更多类似于fail "To err is human" :: Maybe t 的内容,这将导致Nothing

标签: haskell monads


【解决方案1】:

在行中

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)

【讨论】:

  • 我个人会将最后一个表达式键入检查为Monad m => m (Maybe a)。我不确定 GHCi 在哪里推断(m ~ Maybe)
【解决方案2】:

两者的区别:

*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

【讨论】:

    猜你喜欢
    • 2019-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 1970-01-01
    • 2017-06-28
    • 2021-11-06
    • 1970-01-01
    相关资源
    最近更新 更多