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
foldif you try to accumulate something with different type than container (SortedSet!=Int) in your case. Look at signaturefold:it takes accumulator with type
A1and combiner function(A1, A1) => A1which combines twoA1elements.In your case is better to use
foldLeftwhich takes accumulator with different type than container:it accumulates some
Bvalue using seedzand combiner fromBandAtoB.In your case I would like to use
LinkedHashSetit keeps the order of added elements and remove duplicates, look:and after folding just use
toSeqbe careful, lambda
_ + _is just syntactic sugar for combiner: