gpt4 book ai didi

scala - Dotty中给出的如何使用?

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

我在看 Dotty Contextual Abstractions 下的文档页面,我看到了 Given Instances .

Given instances (or, simply, "givens") define "canonical" values of certain types that serve for synthesizing arguments to given clauses. Example:


trait Ord[T] {
def compare(x: T, y: T): Int
def (x: T) < (y: T) = compare(x, y) < 0
def (x: T) > (y: T) = compare(x, y) > 0
}

given intOrd: Ord[Int] {
def compare(x: Int, y: Int) =
if (x < y) -1 else if (x > y) +1 else 0
}

given listOrd[T]: (ord: Ord[T]) => Ord[List[T]] {

def compare(xs: List[T], ys: List[T]): Int = (xs, ys) match {
case (Nil, Nil) => 0
case (Nil, _) => -1
case (_, Nil) => +1
case (x :: xs1, y :: ys1) =>
val fst = ord.compare(x, y)
if (fst != 0) fst else compare(xs1, ys1)
}
}

但是这个例子来自 docs从不解释如何使用 given .我拉了测试 Dotty示例项目并尝试使用它,但我不太明白。

是新关键字吗?我们进口吗?或者我错过了什么。

最佳答案

这是使用 given 的示例实例。假设我们想比较两个整数,看看哪个比另一个大。我们可以利用已经定义的 intOrd上面写:

def whichIsBigger[T](x: T, y: T)(given ord: Ord[T]): String = {
ord.compare(x, y) match {
case -1 => s"$x is less than $y"
case 0 => s"$x and $y are equal"
case 1 => s"$x is greater than $y"
}
}

println(whichIsBigger(2, 1))

其中产生:
2 is greater than 1

我们能够这样做是因为在作用域中有一个命名的给定实例,否则编译器会提示它没有 Ord[Int] .

Is it a new keyword ? Do we import it ? Or am I missing something.



它是一个新关键字,用于替换 implicit 的特定部分。 Scala 2 中的定义。如果这是 Scala 2,我们会这样写:
implicit val intOrd: Ord[Int] = new Ord[Int] {
def compare(x: Int, y: Int) =
if (x < y) -1 else if (x > y) 1 else 0
}

def whichIsBigger[T](x: T, y: T)(implicit ord: Ord[T]): String

关于scala - Dotty中给出的如何使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59456843/

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