How to make a scala collection contain unique elements? ("unique" defined) -


say have list follows:

val l = list( (1, 2, "hi"), (1, 3, "hello"), (2, 3, "world"), (1, 2, "hello") ) 

i want make elements of l distinct ignoring 3rd element of tuple. is, 2 elements of l considered same if first 2 components same.

so makedistinct(l) should return

list( (1, 2, "hi"), (1, 3, "hello"), (2, 3, "world") ) 

what scala-like , generic way implement makedistinct

edit: free choose drop, , ordering need not preserved.

if want lists, use groupby:

l.groupby(x => (x._1, x._2)).map(kv => kv._2.head).tolist 

if want generic collection types:

scala> import scala.collection.generic.canbuildfrom import scala.collection.generic.canbuildfrom  scala> def distinct[a, b, c, cc[x] <: traversable[x]](xs: cc[(a, b, c)])(implicit cbf: canbuildfrom[nothing, (a, b, c), cc[(a, b, c)]]): cc[(a, b, c)] = xs.groupby(x => (x._1, x._2)).map(kv => kv._2.head).to[cc] warning: there 1 feature warnings; re-run -feature details distinct: [a, b, c, cc[x] <: traversable[x]](xs: cc[(a, b, c)])(implicit cbf: scala.collection.generic.canbuildfrom[nothing,(a, b, c),cc[(a, b, c)]])cc[(a, b, c)]  scala> distinct(list((1, 2, "ok"), (1, 3, "ee"), (1, 2, "notok"))) res0: list[(int, int, string)] = list((1,3,ee), (1,2,ok)) 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -