Guest User

Untitled

a guest
Aug 15th, 2018
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. /* This object contains some generic collections ops that can be useful for filtering */
  2. object CollectionOps {
  3.  
  4. implicit class IteratorOps[V](val iterator: Iterator[V]) extends AnyVal {
  5.  
  6. /* Similar to the Stream's .groupBy, but assuming that groups are contiguous. Another difference is that it returns the key corresponding to each group. */
  7. // NOTE: The original iterator should be discarded after calling this method
  8. def contiguousGroupBy[K](getKey: V => K): Iterator[(K, Seq[V])] = new Iterator[(K, Seq[V])] {
  9. /* The definition is very straightforward: we keep the `rest` of values and on each `.next()` call bite off the longest prefix with the same key */
  10.  
  11. /* Buffered iterator allows to look ahead without removing the next element */
  12. private val rest: BufferedIterator[V] = iterator.buffered
  13.  
  14. // NOTE: this is so simple, because of the contiguous grouping assumpltion
  15. def hasNext: Boolean = rest.hasNext
  16.  
  17. def next(): (K, Seq[V]) = {
  18. val key = getKey(rest.head)
  19.  
  20. key -> groupOf(key)
  21. }
  22.  
  23. @annotation.tailrec
  24. private def groupOf_rec(key: K, acc: Seq[V]): Seq[V] = {
  25. if ( rest.hasNext && getKey(rest.head) == key )
  26. groupOf_rec(key, rest.next() +: acc)
  27. else acc
  28. }
  29.  
  30. private def groupOf(key: K): Seq[V] = groupOf_rec(key, Seq())
  31. }
  32. }
  33.  
  34. implicit class MapOp[K, V](val m: Map[K, Iterable[V]]) extends AnyVal {
  35.  
  36. /* From Map[K, Seq[V]] to Map[V, Seq[K]],
  37. applying given function (`identity` by default)
  38. */
  39. def trans[FK, FV](f: ((K, V)) => (FK, FV)): Map[FV, Seq[FK]] =
  40. m.foldLeft(Map[FV, Seq[FK]]()) { case (acc, (k, vs)) =>
  41.  
  42. vs.foldLeft(acc) { (accc, v) =>
  43.  
  44. val (fk, fv) = f(k -> v)
  45. val fks = accc.get(fv).getOrElse( Seq() )
  46.  
  47. accc.updated(fv, fk +: fks)
  48. }
  49. }
  50.  
  51. def trans: Map[V, Seq[K]] = trans(identity[(K, V)])
  52. }
  53.  
  54. }
Add Comment
Please, Sign In to add comment