scala-collections

How does the type inferencer work on reduceLeft?

我们两清 提交于 2019-12-22 10:14:31
问题 Further to my other question about reduceLeft , the signature of reduceLeft on Seq is def reduceLeft [B >: A] (f: (B, A) ⇒ B): B and we can call it with expressions such as List(1,2,3,4) reduceLeft (_ + _) In this example A is Int , so reduceLeft expects a Function2[B >: Int, Int, B] . Regardless of how reduceLeft works (which is irrelevant), how does the type inferencer know that B has a + method, when it could be of type Any ? 回答1: I think the section 6.26.4 Local Type Inference of the spec

Preferred Scala collection for progressively removing random items?

烈酒焚心 提交于 2019-12-22 09:11:47
问题 I have an algoritm which takes many iterations, each of which scores items in a collection and removes the one with the highest score. I could populate a Vector with the initial population, continually replacing it as a var , or choose a mutable collection as a val . Which of the mutable collections would best fit the bill? 回答1: You could consider a DoubleLinkedList, which has a convenient remove() method to remove the current list cell. 回答2: I think a Map (or its close relative, the Set )

Transpose on infinite stream loops forever

假装没事ソ 提交于 2019-12-22 08:26:44
问题 Consider the following: Stream.continually(List(1,2,3)).transpose You would expect to get something equivalent to: Stream( Stream.continually(1), Stream.continually(2), Stream.continually(3) ) However, the upper construct loops infinitely. Is there a workaround for this? Is this to be considered a bug? Question came up discussing this answer. EDIT I know that a function like this writable, see the following example. But is there something in the library? def myTranspose[A,B](in: Stream[A])

Scala Seq - accept only elements of the same subtype

岁酱吖の 提交于 2019-12-22 07:08:02
问题 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

Scala equivalent of new HashSet(Collection)

南楼画角 提交于 2019-12-22 04:12:27
问题 What is the equivalent Scala constructor (to create an immutable HashSet ) to the Java new HashSet<T>(c) where c is of type Collection<? extends T> ?. All I can find in the HashSet Object is apply . 回答1: There are two parts to the answer. The first part is that Scala variable argument methods that take a T* are a sugaring over methods taking Seq[T]. You tell Scala to treat a Seq[T] as a list of arguments instead of a single argument using "seq : _*". The second part is converting a Collection

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

情到浓时终转凉″ 提交于 2019-12-22 04:08:04
问题 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

Unmodifiable view of a mutable Scala collection

妖精的绣舞 提交于 2019-12-22 03:53:12
问题 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

Scala collection filter by type

旧城冷巷雨未停 提交于 2019-12-21 19:39:15
问题 im new to scala and ran into the following problem: I want to get a subcollection of an existing collection that only contains elements of a specific type. The following works: class C(val name : String) class D(name : String) extends C(name) { } val collection = Set[C](new C("C1"),new D("D1"),new C("C2"),new D("D2")) collection.collect{case d : D => d}.size must be === 2 // works But when i try to extend the collection classes with a method "onlyInstancesOf[Type]" this does not work. First

Scala filter on a list by index

不问归期 提交于 2019-12-21 12:29:16
问题 I wanted to write it functionally, and the best I could do was: list.zipWithIndex.filter((tt:Tuple2[Thing,Int])=>(tt._2%3==0)).unzip._1 to get elements 0, 3, 6,... Is there a more readable Scala idiom for this? 回答1: If efficiency is not an issue, you could do the following: list.grouped(3).map(_.head) Note that this constructs intermediate lists. Alternatively you can use a for-comprehension: for { (x,i) <- list zipWithIndex if i % 3 == 0 } yield x This is of course almost identical to your

Scala: Contains in mutable and immutable sets

倾然丶 夕夏残阳落幕 提交于 2019-12-21 09:19:18
问题 I've discovered a strange behavior for mutable sets which I cannot understand: I have a object which I want to add to a set. The equals method for the class is overridden. When I add two different objects to the set, which produces the same output for equals method, I get a different behavior between mutable and immutable sets for the contains method. Here is the code snippet: class Test(text:String){ override def equals(obj:Any) = obj match { case t: Test => if (t.text == this.text) true