我有此代码:
def distinct(seq: Seq[Int]): Seq[Int] =
seq.fold(SortedSet[Int]()) ((acc, i) => acc + i)
我想遍历seq
,删除重复项(保留第一个数字)并保持数字顺序。我的想法是使用SortedSet
作为附件。
但是我得到了:
类型不匹配:
必需:字符串
找到:任何
如何解决? (我也不知道如何在最终迭代中将SortedSet
转换为Seq
,因为我想让distinct
返回seq
)
p.s。而不使用标准的seq
distinct
方法
答案 0 :(得分:2)
如果您尝试堆积与容器类型不同的东西(fold
!= SortedSet
),则不应使用Int
。查看签名fold
:
def fold[A1 >: A](z: A1)(op: (A1, A1) => A1): A1
它需要类型为A1
的累加器和组合两个(A1, A1) => A1
元素的组合器函数A1
。
在您的情况下,最好使用foldLeft
,它使用与容器不同类型的累加器:
def foldLeft[B](z: B)(op: (B, A) => B): B
它使用 seed B
和组合器从z
和B
到A
累积一些B
值。
在您的情况下,我想使用LinkedHashSet
来保持添加元素的顺序并删除重复项,请看:
import scala.collection.mutable
def distinct(seq: Seq[Int]): Seq[Int] = {
seq.foldLeft(mutable.LinkedHashSet.empty[Int])(_ + _).toSeq
}
distinct(Seq(7, 2, 4, 2, 3, 0)) // ArrayBuffer(7, 2, 4, 3, 0)
distinct(Seq(0, 0, 0, 0)) // ArrayBuffer(0)
distinct(Seq(1, 5, 2, 7)) // ArrayBuffer(1, 5, 2, 7)
折叠后,只需使用toSeq
请注意,lambda _ + _
只是合路器的语法糖:
(linkedSet, nextElement) => linkedSet + nextElement
答案 1 :(得分:0)
我只会在您的cb.SelectedValueBinding = new Binding("AColumnInYourDataTable");
cb.SelectedValuePath = "NameOfThePropertyOfTThatHoldsTheValue";
cb.DisplayMemberPath = "NameOfAPropertyOfTThatHoldsTheDisplayName";
上致电distinct
。您可以在Seq
的源代码中看到,SeqLike
只会遍历distinct
并跳过已经看到的数据:
Seq