Haskell 中 MonadPlus 的默认类型评估是什么? [英] What is the default type evaluation of MonadPlus in Haskell?
问题描述
我有以下代码:
import Control.Monad
coin :: MonadPlus m => m Int
coin = return 0 `mplus` return 1
如果我在解释器上计算 coin :: Maybe Int
,它会显示 Just 0
.这是正常的,因为 May 是作为 MonadPlus 的实例实现的.
If I evaluate coin :: Maybe Int
on the interpreter, it prits Just 0
. That's normal because of the implementation of Maybe as instance of MonadPlus.
如果我在解释器上计算 coin :: [Int]
,它会打印 [0, 1]
,因为 mplus
的实现列表中是 append
.
If I evaluate coin :: [Int]
on the interpreter, it prints [0, 1]
, because the implementation of mplus
on list is an append
.
但是如果我计算 coin
,没有任何类型装饰器,它打印 0
.为什么?解释器转换"什么类型的 coin
来评估它?
But if I evaluate coin
, without any type decorators, it prints 0
. Why? What type does the interpreter 'converts' coin
to evaluate it?
此代码摘自:http://homes.sice.indiana.edu/ccshan/rational/S0956796811000189a.pdf
推荐答案
是的,这是 ghci 的一个没有很好记录的角落.当你在 ghci 中输入一个表达式时,它使用表达式的类型来决定要做什么:
Yeah, this is a not super-well documented corner of ghci. When you enter an expression into ghci, it uses the expression's type to decide what to do:
IO()
:运行动作,什么都不做.显示一个 =>IO a
:运行动作并打印
结果.- 任何其他
IO a
:运行操作,不做进一步的操作. - 其他:用
print
包裹整个表达式.
IO ()
: Run the action, do nothing further.Show a => IO a
: Run the action andprint
the result.- any other
IO a
: Run the action, do nothing further. - anything else: wrap the whole expression with
print
.
它如何决定事物具有这些类型中的哪一种?简单:它尝试统一上述每个签名的表达式类型,并解决所有结果约束.(对于行家:这是对扩展默认规则的补充!这解释了为什么它似乎默认了 m
,即使标准默认规则和扩展默认规则都不是默认规则说明默认使用什么.)
How does it decide which of these types a thing has? Easy: it tries to unify the type of your expression which each of the above signatures in turn and solve all resulting constraints. (For the cognoscenti: this is in addition to the extended defaulting rules! This explains why it appears to be defaulting the m
, even though neither the standard defaulting rules nor the extended defaulting rules say what default to use.)
因此,由于您的表达式不与 IO ()
统一,但与 Show a => 统一;IO a
,ghci在统一时发现m ~ IO
(和a ~ Int
),发现有一个MonadPlus IO
(和一个 Show Int
) 实例来解决约束、运行您的操作并打印结果.
So, since your expression does not unify with IO ()
but does unify with Show a => IO a
, ghci finds m ~ IO
(and a ~ Int
) during unification, discovers that there is a MonadPlus IO
(and a Show Int
) instance to resolve the constraints, runs your action, and prints the result.
这篇关于Haskell 中 MonadPlus 的默认类型评估是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!