Haskell 中 MonadPlus 的默认类型评估是什么? [英] What is the default type evaluation of MonadPlus in Haskell?

查看:23
本文介绍了Haskell 中 MonadPlus 的默认类型评估是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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:

  1. IO():运行动作,什么都不做.
  2. 显示一个 =>IO a:运行动作并打印结果.
  3. 任何其他IO a:运行操作,不做进一步的操作.
  4. 其他:用 print 包裹整个表达式.
  1. IO (): Run the action, do nothing further.
  2. Show a => IO a: Run the action and print the result.
  3. any other IO a: Run the action, do nothing further.
  4. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆