gpt4 book ai didi

scala - 类型参数推断 + 高阶类型 + 类型类 = :-(

转载 作者:行者123 更新时间:2023-12-01 17:33:05 25 4
gpt4 key购买 nike

import scalaz._; import Scalaz._

def foo[M[_]:MonadPlus,A](a:A) = a.point[M]
// foo: [M[_], A](a: A)(implicit evidence$1: scalaz.MonadPlus[M])M[A]

def bar1[M[_]:MonadPlus](i:Int): M[Int] =
foo(i) // <-- error: ambiguous implicit values

// this works, but why? Isn't it just the same?
def bar2[M[_]:MonadPlus](i:Int): M[Int] =
foo(i)(implicitly[MonadPlus[M]])

def bar3[M[_]](i:Int)(implicit m:MonadPlus[M]): M[Int] =
foo(i)(m) // slightly less surprising that this works

def bar4[M[_]:MonadPlus](i:Int): M[Int] =
foo[M,Int](i) // this also works, but why?

构建.sbt:

scalaVersion := "2.9.2"

libraryDependencies += "org.scalaz" %% "scalaz-core" % "7.0.0-M5"

(尽管我在 2.10.0-RC3 中得到了相同的结果)

最佳答案

如果您简单地编写以下内容,您会收到相同的错误消息:

import scalaz._; import Scalaz._

def foo[M[_]:MonadPlus,A](a:A) = a.point[M]

foo(1) // <-- error: ambiguous implicit values
// both value listInstance ...
// and value optionInstance ...

我的理解是编译器尝试对 bar1 的“主体”进行类型检查方法并且没有考虑可能有 MonadPlus[M]范围内的实例(由 bar 定义带来),它已经找到 2 个特定的 MonadPlus[M]适合 foo 的实例(listInstance 和 optionInstance)调用。在这个阶段,它只是声明了一个歧义。

然后在 bar2bar3您在 bar4 中明确指定要使用的实例您给出的类型参数为 MInt这在 foo 上并不含糊。调用,因为具有这些约束的唯一隐含范围是 implicitly[MonadPlus[M]] .

关于scala - 类型参数推断 + 高阶类型 + 类型类 = :-(,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13691416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com