如何在Dotty中使用给定的? [英] How to use given in Dotty?

查看:113
本文介绍了如何在Dotty中使用给定的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was looking at Dotty docs under Contextual Abstractions page and I saw the 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示例项目并尝试使用它,但是我不太理解.

But this example from docs never explains how to use given. I pulled the test Dotty example project and try yo use it, but I don't quite understand it.

这是一个新关键字吗?我们导入吗?还是我错过了什么.

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

推荐答案

以下是使用given实例的示例.假设我们要比较两个整数,然后看哪个大于另一个.我们可以利用上面已经定义的intOrd并编写:

Here's an example of using the given instance. Let's say we want to compare two integers, and see which is bigger than the other. We can leverage the already defined intOrd above and write:

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].

We were able to do this because there was a named given instance in scope, otherwise, the compiler would have complained it doesn't have an Ord[Int].

这是一个新关键字吗?我们导入吗?还是我错过了什么?

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

这是一个新关键字,它替换了Scala 2中implicit定义的特定部分.如果这是Scala 2,我们将编写为:

It is a new keyword, one which replaces a specific part of implicit definition in Scala 2. If this was Scala 2, we would have written:

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

这篇关于如何在Dotty中使用给定的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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