I have this code:
def distinct(seq: Seq[Int]): Seq[Int] =
seq.fold(SortedSet[Int]()) ((acc, i) => acc + i)
I want to iterate over seq
, delete duplicates (keep the first number) and keep order of the numbers. My idea was to use a SortedSet
as an acc.
But I am getting:
Type mismatch:
Required: String
Found: Any
How to solve this? (I also don't know how to convert SortedSet
to Seq
in the final iteration as I want distinct
to return seq
)
p.s. without using standard seq
distinct
method
You shouldn't use
fold
if you try to accumulate something with different type than container (SortedSet
!=Int
) in your case. Look at signaturefold
:it takes accumulator with type
A1
and combiner function(A1, A1) => A1
which combines twoA1
elements.In your case is better to use
foldLeft
which takes accumulator with different type than container:it accumulates some
B
value using seedz
and combiner fromB
andA
toB
.In your case I would like to use
LinkedHashSet
it keeps the order of added elements and remove duplicates, look:and after folding just use
toSeq
be careful, lambda
_ + _
is just syntactic sugar for combiner: