SortedSet折叠类型不匹配

时间:2020-10-09 05:47:37

标签: scala functional-programming fold sortedset

我有此代码:

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方法

Online code

2 个答案:

答案 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和组合器从zBA累积一些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
相关问题