如何按字典顺序比较scala元组? [英] How to lexicographically compare scala tuples?
问题描述
给定两个相同数量的元组,我如何按字典顺序比较它们?看起来这应该像下面的代码片段一样简单,但事实并非如此.有什么简单的例子来说明如何做吗?
Given two tuples of the same arity, how can I lexicographically compare them? It seems like this should be as simple as in the following snippet, but it isn't. Any simple example of how to do it?
var x = (1,2,3) < (1,2,4)
如果它们是列表,我可以定义一个递归函数来比较列表的头部,直到找到差异或列表的结尾,但我认为我不能对元组这样做.
Were they lists, I could define a recursive function that would compare the lists' head until a difference or the end of a list was found, but I don't think I could do that for tuples.
推荐答案
不简单,因为while
It's not simple because while
var x = (1,2,3) < (1,2)
看起来很简单,
var x = (1,false,3) < (1,2)
不是.你如何处理非有序类型?如何处理同一个元组位置的不同类型?
is not. How do you deal with non-ordered types? How do you deal with different types in the same tuple position?
您是否要求所有类型都相同?在这种情况下,您没有元组.元组的全部意义在于它的元数是固定的(你静态地知道它有多大)并且每个元素可以是不同的类型.
Do you mandate all types to be the same? In that case, you do not have a tuple. The whole point of a tuple is that its arity is fixed (you statically know how big it is) and each element can be of a different type.
如果我发现自己遇到了这个问题——而且我会非常努力地避免——我会抓住 Shapeless,将元组转换成 HLists 之类的东西,然后尝试进行比较.
If I found myself with that problem -- and I'd try very hard not to -- I'd grab Shapeless, convert the tuples into something like HLists, and then try to compare on that.
编辑
啊,现在容易多了:
import scala.math.Ordering.Implicits._
var x = (1,2,3) < (1,2,4)
这些额外的隐式不会自动可用,因为它们在某些情况下会导致隐式发散.
These extra implicits are not automatically available because they can result in diverging implicits under some circumstances.
这篇关于如何按字典顺序比较scala元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!