scala-collections

Can I create a collection in Scala that uses different equals/hashCode/compare implementations?

二次信任 提交于 2019-12-05 12:09:37
I'm looking for as simple way to create an identity set. I just want to be able to keep track of whether or not I've "seen" a particular object while traversing a graph. I can't use a regular Set because Set uses "==" (the equals method in Scala) to compare elements. What I want is a Set that uses "eq." Is there any way to create a Set in Scala that uses some application-specified method for testing equality rather than calling equals on the set elements? I looked for some kind of "wrapEquals" method that I could override but did not find it. I know that I could use Java's IdentityHashMap, but

Efficient groupwise aggregation on Scala collections

╄→гoц情女王★ 提交于 2019-12-05 11:03:13
I often need to do something like coll.groupBy(f(_)).mapValues(_.foldLeft(x)(g(_,_))) What is the best way to achieve the same effect, but avoid explicitly constructing the intermediate collections with groupBy ? You could fold the initial collection over a map holding your intermediate results: def groupFold[A,B,X](as: Iterable[A], f: A => B, init: X, g: (X,A) => X): Map[B,X] = as.foldLeft(Map[B,X]().withDefaultValue(init)){ case (m,a) => { val key = f(a) m.updated(key, g(m(key),a)) } } You said collection and I wrote Iterable , but you have to think whether order matters in the fold in your

Implement a scala collection so that map, filter, etc. produce the right type

与世无争的帅哥 提交于 2019-12-05 11:01:49
I'm trying to implement a default valued map , and I'd like filters, maps, etc. over a DefaultingMap to also produce a DefaultingMap whenever possible. Here's my initial implementation: class DefaultingMap[K, V](defaultValue: => V) extends mutable.HashMap[K, V] with mutable.MapLike[K, V, DefaultingMap[K, V]] { override def empty = new DefaultingMap[K, V](defaultValue) override def default(key: K): V = { val result = this.defaultValue this(key) = result result } } I get objects of type DefaultingMap when I use filter , but not when I use map : scala> val counter = new DefaultingMap[Char, Int](0

Scala Seq - accept only elements of the same subtype

喜夏-厌秋 提交于 2019-12-05 09:10:09
Assuming I have a type hierarchy like the following: trait Color case class Red(r: String) extends Color case class Green(g: String) extends Color Is it possible to create a method that accepts a Seq[Color] that contains elements of either all Red , or either all Green , but not both? For example in the following code: def process[T](colors: Seq[T]) = colors.size process(Seq(Red("a"), Green("g"))) what should [T] be so that the above does not type-check? Edit The original problem is the following: I am trying to devise a JSON API for nested queries. I have come up with the following design:

Conversion from scala parallel collection to regular collection

╄→尐↘猪︶ㄣ 提交于 2019-12-05 08:55:42
问题 I'm trying to convert back from a parallel collection to a regular map. According to the api, if I call toMap on any appropriately defined parallel collection, it's supposed to return a standard Map, but it's returning ParMap over a flattened collection of iterables. I have a val task: Stream[Future[Iterable[Tuple2[String, String]]]] And from which I get: val res: ParSeq[Iterable[Tuple2[String, String]]] = tasks.par.map(f => f.apply()) Finally: val finalresult = res.flatten.toMap

How to find the number of (key , value) pairs in a map in scala?

醉酒当歌 提交于 2019-12-05 08:47:47
问题 I need to find the number of (key , value) pairs in a Map in my Scala code. I can iterate through the map and get an answer but I wanted to know if there is any direct function for this purpose or not. 回答1: you can use .size scala> val m=Map("a"->1,"b"->2,"c"->3) m: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2, c -> 3) scala> m.size res3: Int = 3 回答2: Use Map#size: The size of this traversable or iterator. The size method is from TraversableOnce so, barring infinite

How do you rotate (circular shift) of a Scala collection

蹲街弑〆低调 提交于 2019-12-05 08:12:48
I can do this quite easily, and cleanly, using a for loop. For instance, if I wanted to traverse a Seq from every element back to itself I would do the following: val seq = Seq(1,2,3,4,5) for (i <- seq.indices) { for (j <- seq.indices) { print(seq(i + j % seq.length)) } } But as I'm looking to fold over the collection, I'm wondering if there is a more idiomatic approach. A recursive approach would allow me to avoid any var s. But basically, I'm wondering if something like the following is possible: seq.rotatedView(i) Which would create a rotated view, like rotating bits (or circular shift).

How to make Scala's immutable collections hold immutable objects

大兔子大兔子 提交于 2019-12-05 06:01:05
I'm evaluating Scala and am having a problem with its immutable collections. I want to make immutable collections, which are completely immutable, right down through all the contained objects, the objects they reference, ad infinitum. Is there a simple way to do this? The code on http://www.finalcog.com/immutable-containers-scala illustrates what I'm trying to achieve, and a nasty work around (ImmutablePoint). The problem with the workaround is that every time I want to change an object I have to manually make a new copy. I understand that the runtime will have to implement copy-on-write, but

Scala SortedSet - sorted by one Ordering and unique by something else?

一个人想着一个人 提交于 2019-12-05 02:51:08
Say I have a set of Strings that I want to be ordered by length but unique by the normal String uniqueness. What I mean is that I that I could have more than one String of same length in the Set , but that they should be sorted by length. I want to express the ordering like this: val orderByLength = Ordering[Int].on[String](_ length) which I think looks really nice. But if I were to throw this into a SortedSet, say like this: scala> val s = SortedSet("foo", "bar")(orderByLength) s: scala.collection.immutable.SortedSet[java.lang.String] = TreeSet(bar) I only get 'bar'. This is because the

Unmodifiable view of a mutable Scala collection

爷,独闯天下 提交于 2019-12-05 01:41:49
I have a class with a private field that is a mutable collection. The field in this particular instance is an ArrayBuffer , although my question extends to any finite, ordered, random-access collection type. I want to expose this field without permitting others to modify it. In Java I would add a method like: private List<T> theList; public List<T> getList() { return Collections.unmodifiableList(theList); } In Java we just accept that the result is a List that doesn't fully implement the List interface because #add and friends throw UnsupportedOperationException . In Scala, I would expect to