Efficient building of Set in Scala, without o(n^2), if I know there are no duplicates -
i required pass set in scala series of functions. don't have choice, must set.
i receive big list of json values:
scala.list[jsonast.jvalue]
the naive way use toset:
val input : scala.list[jsonast.jvalue] val myset = input.toset
but can expensive performance perspective. way toset works starts first element in list, , adds following ones one-by-one. each time, scans set ensure value isn't there.
let's assume know fact there aren't duplicates. there way me create set more efficiently? ideally, copying list set. no changes in order or contents.
as ziggystar pointed out, can have o(1) performance when converting list
set
if willing use adapter, , trade fast conversion (o(1)) set poor performance when calling contains
(o(n)).
if acceptable trade off use case, can use this:
import scala.collection.abstractset class setadapter[a](val self: seq[a]) extends abstractset[a] { def +(elem: a): setadapter[a] = if (self.contains(elem)) else new setadapter(self :+ elem) def -(elem: a): setadapter[a] = new setadapter(self.filternot(_ == elem)) def contains(elem: a): boolean = self.contains(elem) // assumes not duplicates in self, otherwise // incorrectly iterate several times on equal values, set not supposed def iterator: iterator[a] = self.iterator } implicit class assetops[a](val seq: seq[a]) extends anyval { def asset() = new setadapter[a](seq) }
quick repl test check works expected:
scala> val s = l.asset s: setadapter[int] = set(1, 3, 4, 8, 12) scala> s + 6 res8: setadapter[int] = set(1, 3, 4, 8, 12, 6) scala> s - 8 res9: setadapter[int] = set(1, 3, 4, 12)
in example, you'd have this:
val input : scala.list[jsonast.jvalue] val myset = input.asset
Comments
Post a Comment