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
.这是正常的,因为可能将Maybe作为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
.为什么?解释器将'c6>转换为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 ()
:运行操作,什么都不做. -
Show a => IO a
:运行操作并print
结果. - 其他任何
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
.
它如何确定事物具有哪种类型?简单:它试图统一您的表达式的类型,而上述每个签名又依次解决所有产生的约束. (对于cognoscenti:这是扩展默认规则的 !这解释了为什么它似乎是默认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
(和
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屋!