PrimosK
PrimosK

Reputation: 13918

Looking for the best solution

Consider this list composed of objects which are instances of case classes:

A, B, Opt(A),C, Opt(D), F, Opt(C), G, Opt(H)

I wan to normalize this list to get this result:

A, B, C, Opt(D), F, G, Opt(H)

As you see, if there are elements A and Opt(A) I replace them with just A or said other way, I have to remove OPT(A) element.

I would like:

Upvotes: 0

Views: 142

Answers (3)

drexin
drexin

Reputation: 24423

This might be a little more concise, as filtering is what you want ;-):

scala> List(1,2,3,Some(4),5,Some(5))
res0: List[Any] = List(1, 2, 3, Some(4), 5, Some(5))

scala> res0.filter {
     | case Some(x) => !res0.contains(x)
     | case _ => true
     | }
res1: List[Any] = List(1, 2, 3, Some(4), 5)

edit: For large collections it might be good to use a toSet or directly use a Set.

Upvotes: 2

Luigi Plinge
Luigi Plinge

Reputation: 51109

If you don't care about order then efficiency leads you to use a Set:

xs.foldLeft(Set.empty[Any])({ case (set, x) => x match {
  case Some(y) => if (set contains y) set else set + x
  case y => if (set contains Some(y)) set - Some(y) + y else set + y
}}).toList

Alternatively:

val (opts, ints) = xs.toSet.partition(_.isInstanceOf[Option[_]])
opts -- (ints map (Option(_))) ++ ints toList

Upvotes: 1

missingfaktor
missingfaktor

Reputation: 92056

Not the most efficient solution, but certainly a simple one.

scala> case class Opt[A](a: A)
defined class Opt

scala> val xs = List(1, 2, Opt(1), 3, Opt(4), 6, Opt(3), 7, Opt(8))
xs: List[Any] = List(1, 2, Opt(1), 3, Opt(4), 6, Opt(3), 7, Opt(8))

scala> xs flatMap {
     |   case o @ Opt(x) => if(xs contains x) None else Some(o)
     |   case x => Some(x)
     | }
res5: List[Any] = List(1, 2, 3, Opt(4), 6, 7, Opt(8))

Upvotes: 2

Related Questions