gpt4 book ai didi

Scala:类型推断和子类型/更高种类的类型

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

我一直在使用 Scalaz,以便在 scala 中获得一点 Haskell 的感觉。到了解 scala 中的工作原理 我开始自己实现各种代数结构,并遇到了 Scalaz 人员提到的一种行为。

这是我实现仿函数的示例代码:

trait Functor[M[_]] {
def fmap[A, B](a: M[A], b: A => B): M[B]
}

sealed abstract class Foo[+A]
case class Bar[A]() extends Foo[A]
case class Baz[A]() extends Foo[A]

object Functor {

implicit val optionFunctor: Functor[Option] = new Functor[Option]{
def fmap[A, B](a: Option[A], b: A => B): Option[B] = a match {
case Some(x) => Some(b(x))
case None => None
}
}

implicit val fooFunctor: Functor[Foo] = new Functor[Foo] {
def fmap[A, B](a: Foo[A], b: A => B): Foo[B] = a match {
case Bar() => Bar()
case Baz() => Baz()
}
}
}

object Main {
import Functor._

def some[A](a: A): Option[A] = Some(a)
def none[A]: Option[A] = None

def fmap[M[_], A, B](a: M[A])(b: A => B)(implicit f: Functor[M]): M[B] =
f.fmap(a, b)

def main(args: Array[String]): Unit = {
println(fmap (some(1))(_ + 1))
println(fmap (none)((_: Int) + 1))
println(fmap (Bar(): Foo[Int])((_: Int) + 1))
}
}

我为 Option 编写了一个仿函数实例和一个虚假的 sumtype Foo。问题在于,如果没有显式类型注释或包装方法,scala 无法推断隐式参数

def some[A](a: A): Option[A] = Some(a)

println(fmap (Bar(): Foo[Int])((_: Int) + 1))

Scala 无需这些解决方法即可推断 Functor[Bar] 和 Functor[Some] 等类型。

这是为什么呢?谁能帮我指出语言规范中定义此行为的部分吗?

问候,雷鸟

最佳答案

您要求编译器执行两项任务:fmap 的类型参数的本地类型推断(第 6.26.4 节),以及对隐式参数的隐式搜索(第 7.2 节)f。引用文献为 Scala Reference .

事情大致按以下顺序进行:

fmap[M = ?, A = ?, B = ?](Some(1))(x => x)

// type the arguments of the first parameter section. This is done
// without an expected type, as `M` and `A` are undetermined.
fmap[M = ?, A = ?, B = ?](Some(1): Some[Int])(x => x)(?)

// local type inference determines `M` and `A`
fmap[Some, Int, B = ?](Some(1): Some[Int])(x => x)(?)

// move to the second parameter section, type the argument with the expected type
// `Function1[Int, ?]`. The argument has the type `Function1[Int, Int]`
fmap[Some, Int, ?](Some(1): Some[Int])((x: Int) => x)

// local type inference determines that B = Int
fmap[Some, Int, Int](Some(1): Some[Int])((x: Int) => x)

// search local identifiers, and failing that the implicit scope of type `Functor[Some]]`, for an implicit
// value that conforms to `Functor[Some]`
fmap[Some, Int, Int](Some(1): Some[Int])((x: Int) => x)(implicitly[Functor[Some]])

隐式搜索Functor[Some]失败; Functor[Option] 不符合要求。

关于Scala:类型推断和子类型/更高种类的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4915910/

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