Scala Tour 隐式转换示例 [英] Scala Tour Implicit Conversion Example
问题描述
我很难理解这段代码到底做了什么:
I am having a hard time understanding what this piece of code does exactly:
import scala.language.implicitConversions
implicit def list2ordered[A](x: List[A])
(implicit elem2ordered: A => Ordered[A]): Ordered[List[A]] =
new Ordered[List[A]] {
//replace with a more useful implementation
def compare(that: List[A]): Int = 1
}
它来自 Scala Tour,位于隐式转换"部分.我知道 list2ordered
需要一个 List[A]
来自 List(1, 2, 3) <= List(4,5)
和 compare
函数中的that
是右侧.
It comes from the Scala Tour and it is in the section "Implicit Conversions". I understand that list2ordered
takes a List[A]
that comes from the left hand side of List(1, 2, 3) <= List(4, 5)
and that
in compare
function is the right hand side.
然而,为什么 A =>Ordered[A]
而不是 List[A] =>有序[列表[A]]
?我对这段代码的实际作用有点困惑.
However, why is A => Ordered[A]
that and not List[A] => Ordered[List[A]]
? I am a bit confused as to what this piece of code actually does.
推荐答案
你的困惑是可以理解的.示例代码并不是非常有启发性,主要是因为代码,如所呈现的,不需要 A
-to-Ordered[A]
转换.我们可以将其注释掉,一切仍然有效"(如其所是).
Your confusion is understandable. The example code isn't terribly illuminating largely because the code, as presented, doesn't need the A
-to-Ordered[A]
conversion. We can comment it out and everything still "works" (such as it is).
import scala.language.implicitConversions
implicit def list2ordered[A](xs: List[A]
//)(implicit elem2ordered: A => Ordered[A]
): Ordered[List[A]] =
new Ordered[List[A]] {
def compare(ys: List[A]): Int =
1 //this is always greater than that
}
我们甚至可以实现一个有意义的(如果头脑比较简单的话)List
排序,并且仍然不需要 A
-to-Ordered[A]
转化.
We can even implement a meaningful (if rather simple minded) List
ordering and still not need the A
-to-Ordered[A]
conversion.
import scala.language.implicitConversions
implicit def list2ordered[A](xs: List[A]
//)(implicit elem2ordered: A => Ordered[A]
): Ordered[List[A]] =
new Ordered[List[A]] {
def compare(ys: List[A]): Int =
xs.length - ys.length //shorter List before longer List
}
但是如果 List
顺序取决于元素顺序,那么我们需要这种转换.
But if List
order depends on element order, then we need that conversion.
import scala.language.implicitConversions
implicit def list2ordered[A](xs: List[A]
)(implicit elem2ordered: A => Ordered[A]
): Ordered[List[A]] =
new Ordered[List[A]] {
//3rd element determines order
def compare(ys: List[A]): Int = (xs.lift(2),ys.lift(2)) match {
case (None,None) => 0
case (None, _) => -1
case (_, None) => 1
case (Some(x), Some(y)) =>
x compare y //implicit conversion needed
}
}
为了说明重点,让我们通过修改所需的转换来简化这种按 3rd-element 排序的排列.
Just to drive home the point, let's simplify this order-by-3rd-element arrangement by modifying the required conversion.
import scala.language.implicitConversions
implicit def list2ordered[A](xs: List[A]
)(implicit elem2ordered: Option[A] => Ordered[Option[A]]
): Ordered[List[A]] =
new Ordered[List[A]] {
def compare(ys: List[A]): Int =
xs.lift(2) compare ys.lift(2) //3rd element determines order
}
这篇关于Scala Tour 隐式转换示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!