Cannot construct a collection of type ...Inclusive[Long] with elements of type Long based on a collection of type ...Inclusive[Long] - scala

I'm not sure I understand why the following happens.
Compiles and works:
With Ints without converting to a List
import scala.util.Random
val xs = 1 to 10
Random.shuffle(xs)
With Longs after converting to a List
import scala.util.Random
val xs = 1L to 10L
Random.shuffle(xs.toList) //<-- I had to materialize it to a list
Doesn't compile
With Longs without converting to a List
val xs = 1L to 10L
Random.shuffle(xs)
This one throws this exception:
Error: Cannot construct a collection of type
scala.collection.immutable.NumericRange.Inclusive[Long] with elements of type
Long based on a collection of type
scala.collection.immutable.NumericRange.Inclusive[Long].
Random.shuffle(xs)
^
I'm curious why? Is that because there is a missing CanBuildFrom or something like that? Is there a good reason why there isn't one?
(scala version 2.11.5)

That's because of both CanBuildFrom(1) and type inference mechanism(2).
1) You may find that genericBuilder of Range/NumericRange (same for Inclusive) is:
genericBuilder[B]: Builder[B, IndexedSeq[B]]
So there is only CanBuildFrom[Range, B, IndexedSeq], which uses this builder. The reason why is simple, you may find it in builder's description:
A builder lets one construct a collection incrementally, by adding elements to the builder with += and then converting to the required collection type with result.
You just can't construct inclusive range incrementally, as it won't be a range anymore then (but still be an IndexedSeq); however, you can do such constructions with Seq.
Just to demonstrate the difference between IndexedSeq and Inclusive
scala> (1 to 5)
res14: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5)
scala> (1 to 5) ++ (7 to 10) //builder used here
res15: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5, 7, 8, 9, 10)
This means that you can't "build" any range, regardless Int (Range) or Long (Numeric) and you should always pass IndexedSeq as To parameter of the builder. However, IndexedSeq is automatically specified for Int (Range), when you pass it to the shuffle function.
2) It's not working for NumericRange.Inclusive[T] because it's a polymorphic type (generic). While, regular Range.Inclusive (not generic) explicitly extends IndexedSeq[Int]. Looking on shuffle signature:
shuffle[T, CC[X] <: TraversableOnce[X]](xs: CC[T])(implicit bf: CanBuildFrom[CC[T], T, CC[T]]): CC[T]
Higher-order type CC is becoming NumericRange.Inclusive here as it's the biggest parametrized type inherited by NumericRange.Inclusive. In case of Range.Inclusive, that was an IndexedSeq (as smaller Range.Inclusive is not generic). So Range.Inclusive just got lucky to be not affected by (1).
Finally, this will work:
scala> Random.shuffle[Long, IndexedSeq](xs)
res8: IndexedSeq[Long] = Vector(9, 3, 8, 6, 7, 2, 5, 4, 10, 1)
scala> Random.shuffle(xs: IndexedSeq[Long])
res11: IndexedSeq[Long] = Vector(6, 9, 7, 3, 1, 8, 5, 10, 4, 2)

Related

How to pass ordering to scala.util.Sorting.quickSort

I'm trying to pass reverse ordering to the scala.util.Sorting.quickSort with this code:
val a = Array(3, 5, 1, 2)
scala.util.Sorting.quickSort(a)(Ordering.Int.reverse)
It doesn't work saying that:
Error: Unit does not take parameters
However, the code like that works:
val a = Array(3, 5, 1, 2)
a.sorted(Ordering.Int.reverse)
I don't understand why the quickSort example doesn't work? The Ordering.Int.reverse produce Ordering[Int] and according to documentation, the quickSort accepts it implicitly.
I'm running with Scala 2.12.7.
Expanding on Yuval Itzchakov's comment, here is the source code for scala.util.Sorting.quickSort:
def quickSort(a: Array[Int]): Unit = java.util.Arrays.sort(a)
A few lines down, another overloaded quicksort is defined as:
def quickSort[K: Ordering](a: Array[K]): Unit = {...
You mean to use this latter one. But when you call quickSort, the compiler is picking the first one which does not accept an Ordering in its parameter list so it complains about extra parameters. You will need to specify type parameter if you are using Int, Double, or Float as explained here. To summarize:
val a : Array[Int] = Array(3, 5, 1, 2)
val b = Array(3L, 5L, 1L, 2L) //Longs do not have this problem!
scala.util.Sorting.quickSort[Int](a)(Ordering.Int.reverse)
scala.util.Sorting.quickSort(b)(Ordering.Long.reverse)
println(a.toList)
println(b.toList)
List(5, 3, 2, 1)
List(5, 3, 2, 1)
According to documentation the signature of method that uses Ordering is:
def quickSort[K](a: Array[K])(implicit arg0: math.Ordering[K]): Unit
Sort array a with quicksort, using the Ordering on its elements. This
algorithm sorts in place, so no additional memory is used aside from
what might be required to box individual elements during comparison.
try this:
scala> val a = Array(3, 5, 1, 2)
a: Array[Int] = Array(3, 5, 1, 2)
scala> scala.util.Sorting.quickSort(a)(Ordering.Int.reverse)
<console>:13: error: Unit does not take parameters
scala.util.Sorting.quickSort(a)(Ordering.Int.reverse)
^
scala> scala.util.Sorting.quickSort[Int](a)(Ordering[Int].reverse)
scala> a
res2: Array[Int] = Array(5, 3, 2, 1)

How to enforce a Collection (Seq, List etc.) to accept only positive integers - Scala

I would ideally like to enforce a Collection in Scala to allow only positive integers. Is there way?
I can achieve it at run time by wrapping a Sequence in a class and verifying it's initialization, but that would mean handling exception at run time. A compile time solution would be nicer.
You can use refined to define a List[Int ## Positive], that is a list of Ints that are greater than zero. refined will then check at compile-time that all elements in your list are positive:
import eu.timepit.refined.auto._
import eu.timepit.refined.numeric.Positive
import shapeless.tag.##
scala> val posInts: List[Int ## Positive] = List(1, 2, 3)
posInts: List[Int ## Positive] = List(1, 2, 3)
If you try to put a non-positive Int in the List, you'll get a compile error:
scala> val posInts: List[Int ## Positive] = List(1, 2, 3, -4)
<console>:43: error: Predicate failed: (-4 > 0).
val posInts: List[Int ## Positive] = List(1, 2, 3, -4)
^

Scala: Can I rely on the order of items in a Set?

This was quite an unplesant surprise:
scala> Set(1, 2, 3, 4, 5)
res18: scala.collection.immutable.Set[Int] = Set(4, 5, 1, 2, 3)
scala> Set(1, 2, 3, 4, 5).toList
res25: List[Int] = List(5, 1, 2, 3, 4)
The example by itself suggest a "no" answer to my question. Then what about ListSet?
scala> import scala.collection.immutable.ListSet
scala> ListSet(1, 2, 3, 4, 5)
res21: scala.collection.immutable.ListSet[Int] = Set(1, 2, 3, 4, 5)
This one seems to work, but should I rely on this behavior?
What other data structure is suitable for an immutable collection of unique items, where the original order must be preserved?
By the way, I do know about distict method in List. The problem is, I want to enforce uniqueness of items (while preserving the order) at interface level, so using distinct would mess up my neat design..
EDIT
ListSet doesn't seem very reliable either:
scala> ListSet(1, 2, 3, 4, 5).toList
res28: List[Int] = List(5, 4, 3, 2, 1)
EDIT2
In my search for a perfect design I tried this:
scala> class MyList[A](list: List[A]) { val values = list.distinct }
scala> implicit def toMyList[A](l: List[A]) = new MyList(l)
scala> implicit def fromMyList[A](l: MyList[A]) = l.values
Which actually works:
scala> val l1: MyList[Int] = List(1, 2, 3)
scala> l1.values
res0: List[Int] = List(1, 2, 3)
scala> val l2: List[Int] = new MyList(List(1, 2, 3))
l2: List[Int] = List(1, 2, 3)
The problem, however, is that I do not want to expose MyList outside the library. Is there any way to have the implicit conversion when overriding? For example:
trait T { def l: MyList[_] }
object O extends T { val l: MyList[_] = List(1, 2, 3) }
scala> O.l mkString(" ") // Let's test the implicit conversion
res7: String = 1 2 3
I'd like to do it like this:
object O extends T { val l = List(1, 2, 3) } // Doesn't work
That depends on the Set you are using. If you do not know which Set implementation you have, then the answer is simply, no you cannot be sure. In practice I usually encounter the following three cases:
I need the items in the Set to be ordered. For this I use classes mixing in the SortedSet trait which when you use only the Standard Scala API is always a TreeSet. It guarantees the elements are ordered according to their compareTo method (see the Ordered trat). You get a (very) small performance penalty for the sorting as the runtime of inserts/retrievals is now logarithmic, not (almost) constant like with the HashSet (assuming a good hash function).
You need to preserve the order in which the items are inserted. Then you use the LinkedHashSet. Practically as fast as the normal HashSet, needs a little more storage space for the additional links between elements.
You do not care about order in the Set. So you use a HashSet. (That is the default when using the Set.apply method like in your first example)
All this applies to Java as well, Java has a TreeSet, LinkedHashSet and HashSet and the corresponding interfaces SortedSet, Comparable and plain Set.
It is my belief that you should never rely on the order in a set. In no language.
Apart from that, have a look at this question which talks about this in depth.
ListSet will always return elements in the reverse order of insertion because it is backed by a List, and the optimal way of adding elements to a List is by prepending them.
Immutable data structures are problematic if you want first in, first out (a queue). You can get O(logn) or amortized O(1). Given the apparent need to build the set and then produce an iterator out of it (ie, you'll first put all elements, then you'll remove all elements), I don't see any way to amortize it.
You can rely that a ListSet will always return elements in last in, first out order (a stack). If that suffices, then go for it.

strange syntax in lambda expression

val (xa, xb) = xs partition ( a > )
What is a > in above code and how is it different from a > _? (assume a is some predefined value)
Any method that expects a function with some argument can be instead passed a one-argument method and, if the types work out, the method will be automatically converted.
So these all are valid:
class C { def go(i: Int) = -i }
val c = new C
List(1,2,3).foreach( println )
List(1,2,3).map( c go )
So, either a has the method > defined, or it can be implicitly converted to something with a > method. For example, this works:
List(1,2,3).partition(2 >)
because (EDIT: one would think this would be true....) there is an implicit conversion from Int to RichInt (the same one that gives you .toFloat and such), and RichInt has a > method defined. partition expects a function that takes Int and returns Boolean and 2 > is a method that takes Int and returns Boolean. So the conversion happens automatically.
(EDIT: but as #Lukas Rytz points out, it's even more tricky than that, because the compiler realizes that it can treat primitive ints specially, so even though > is not really a method on the object 2, because 2 is not an object, and primitives do not have methods, the compiler recognizes that deferring to RichInt would be slower. So, in fact, it just writes a method with the correct bytecode.)
Only if the correct conversion does not happen automatically (because of ambiguity, for example, or because you want to assign it to a variable) do you need to use _ to create a function out of a method. (And then it is not always exactly clear whether you are using _ to convert from method to function, or using _ as a placeholder for the input; fortunately, the result is the same either way.)
It is not different at all, it's just a shorter version.
scala> val a = 10
a: Int = 10
scala> val xs = List(1, 2, 3, 4, 5, 11, 12, 13, 14, 15)
xs: List[Int] = List(1, 2, 3, 4, 5, 11, 12, 13, 14, 15)
scala> val (xa, xb) = xs partition ( a > )
xa: List[Int] = List(1, 2, 3, 4, 5)
xb: List[Int] = List(11, 12, 13, 14, 15)
I think it is actually exactly the same.

Are there any methods included in Scala to convert tuples to lists?

I have a Tuple2 of List[List[String]] and I'd like to be able to convert the tuple to a list so that I can then use List.transpose(). Is there any way to do this? Also, I know it's a Pair, though I'm always a fan of generic solutions.
Works with any tuple (scala 2.8):
myTuple.productIterator.toList
Scala 2.7:
(0 to (myTuple.productArity-1)).map(myTuple.productElement(_)).toList
Not sure how to maintain type info for a general Product or Tuple, but for Tuple2:
def tuple2ToList[T](t: (T,T)): List[T] = List(t._1, t._2)
You could, of course, define similar type-safe conversions for all the Tuples (up to 22).
Using Shapeless -
# import syntax.std.tuple._
import syntax.std.tuple._
# (1,2,3).toList
res21: List[Int] = List(1, 2, 3)
# (1,2,3,4,3,3,3,3,3,3,3).toList
res22: List[Int] = List(1, 2, 3, 4, 3, 3, 3, 3, 3, 3, 3)
Note that type information is not lost using Shapeless's toList.