【问题标题】:What is the type of return 5 in Haskell when no context is given?没有给出上下文时,Haskell 中的 return 5 类型是什么?
【发布时间】:2015-01-13 22:38:55
【问题描述】:

在this question 中,OP 询问表达式 return 5 的类型,并且已经在该问题中给出了答案:它是一个泛型类型,可以通过键入来验证

:t return 5

在 Haskell 解释器中:

return 5 :: (Num a, Monad m) => m a

return 的具体实现取决于它出现的上下文:类型推断会将m 限制为特定的monad,例如Maybe、[]、IO 等。

我还可以通过指定类型来强制解释器选择特定的 monad,例如

Prelude> return 5 :: Maybe Int
Just 5
Prelude> return 5 :: [Int]
[5]

等等。

现在如果我输入表达式 return 5 而不指定类型,我会得到:

Prelude> return 5
5

这让我很吃惊:我更希望解释器告诉我它无法选择 return 的适当实现,因为它无法推断要使用的单子类型。

所以我的问题是:Haskell 在这里使用了哪些特定的 monad?选择这个 monad 的标准是什么?

编辑

感谢您的回答!事实上,如果我尝试编译这个程序:

module Main
where

a = return 5

main :: IO ()
main = putStrLn "This program should not compile"

我收到一个错误:

No instance for (Monad m0) arising from a use of `return'
The type variable `m0' is ambiguous
Relevant bindings include
  a :: m0 Integer (bound at invalid_return.hs:4:1)
Note: there are several potential instances:
  instance Monad ((->) r) -- Defined in `GHC.Base'
  instance Monad IO -- Defined in `GHC.Base'
  instance Monad [] -- Defined in `GHC.Base'
  ...plus one other
In the expression: return 5
In an equation for `a': a = return 5

因此,由于 Jon 解释的原因,它仅适用于 GHCi。

【问题讨论】:

  • 我很惊讶它没有推断出a :: (Num b, Monad m) => m b
  • 如果要编译程序,启用-XNoMonomorphismRestriction :)

标签: haskell monads


【解决方案1】:

单子是IO。这是 GHCi 行为的一个小怪癖。它尝试将您的输入类型与IO a 统一起来;如果成功,它将运行IO 操作并尝试show 结果。如果你给它的不是IO 操作,它只会尝试show 的值。

出于相同的原因,它们会产生相同的输出:

Prelude> "hello"
"hello"
Prelude> print "hello"
"hello"

【讨论】:

  • 好的,结果是IO Int类型。这是有道理的。
  • @Giorgio 不,IO Integer。该数字根据 Haskell 的正常默认规则默认。
  • @kosmikus:好的。谢谢。
  • @kosmikus:看我的额外例子:5 确实得到了类型Integer。
猜你喜欢
  • 1970-01-01
  • 2016-04-16
  • 2020-03-10
  • 2014-12-25
  • 2018-08-09
  • 2012-01-15
  • 1970-01-01
  • 1970-01-01
  • 2016-08-09
相关资源
最近更新 更多