bug
bug copied to clipboard
An improvement to make seq's extractors work for Array and String
Firstly, the following codes compile fine while run with exception:
scala> import scala.collection.SeqLike
import scala.collection.SeqLike
scala> val xs: SeqLike[Char, String] = "abcdef"
xs: scala.collection.SeqLike[Char,String] = abcdef
scala> xs match { case head +: tail => tail }
java.lang.ClassCastException: java.lang.String cannot be cast to scala.collection.SeqLike
at .<init>(<console>:10)
at .<clinit>(<console>)
at .<init>(<console>:7)
at .<clinit>(<console>)
...
Secondly, there are two useful extractors defined in scala.collection.SeqExtractors.scala. But sadly these two extractors does not work for Array and String, and sometimes we do need these function, especially for String.
I would like the followed codes working as expected:
// Expected Result
"abcdef" match { case p +: m :+ q => m } // expect m == "bcde"
Array(1,2,3) match { case h +: tail => tail } //expect tail == Array(2,3)
Here I got an idea to fix the issue by rewriting these two extractors as following:
// SeqExtractors.scala
package scala.collection
/** An extractor used to head/tail deconstruct sequences. */
object +: {
def unapply[T,Coll <% SeqLike[T, Coll]](t: Coll): Option[(T, Coll)] =
if(t.isEmpty) None
else Some(t.head -> t.tail)
}
/** An extractor used to init/last deconstruct sequences. */
object :+ {
/** Splits a sequence into init :+ tail.
* @return Some((init, tail)) if sequence is non-empty. None otherwise.
*/
def unapply[T,Coll <% SeqLike[T, Coll]](t: Coll): Option[(Coll, T)] =
if(t.isEmpty) None
else Some(t.init -> t.last)
}
Imported From: https://issues.scala-lang.org/browse/SI-7108?orig=1 Reporter: Eastsun (eastsun) Affected Versions: 2.11.0-M1
@paulp said: How can this possibly be right:
pt1 match {
// if at least one of the types in an intersection is checkable, use the checkable ones
// this avoids problems as in run/matchonseq.scala, where the expected type is `Coll with scala.collection.SeqLike`
// Coll is an abstract type, but SeqLike of course is not
case RefinedType(ps, _) if ps.length > 1 && (ps exists infer.isCheckable) =>
None
case ptCheckable if infer isUncheckable ptCheckable =>
val classTagExtractor = resolveClassTag(pos, ptCheckable)
if (classTagExtractor != EmptyTree && unapplyMember(classTagExtractor.tpe) != NoSymbol)
Some(classTagExtractor)
else None
case _ => None
}
@scala/collections should this remain open?
Secondly, besides being out of scope or binary incompatible, it doesn't seem to work with new collections.
It does seem to work if you don't care about the result type D, which is WrappedString for String.
I confirmed the 2.12 version extracts a String.
object +: {
def unapply[A, C, D](t: C)(implicit cv: C => SeqOps[A, Any, D]): Option[(A, D)] =
if (t.isEmpty) None
else Some(t.head -> t.tail)
}
object :+ {
def unapply[A, C, D](t: C)(implicit cv: C => SeqOps[A, Any, D]): Option[(D, A)] =
if (t.isEmpty) None
else Some(t.init -> t.last)
}
currently
def unapply[A, CC[_] <: Seq[_], C <: SeqOps[A, CC, C]](t: C with SeqOps[A, CC, C]): Option[(A, C)] = ???
probably there is an important reason SeqOps appears twice.
dotty
object +: :
def unapply[A, C, D](t: C)(using cv: C => SeqOps[A, [_] =>> Any, D]): Option[(A, D)] =
cv(t) match
case t if t.isEmpty => None
case t => Some(t.head -> t.tail)
object :+ :
def unapply[A, C, D](t: C)(using cv: C => SeqOps[A, [_] =>> Any, D]): Option[(D, A)] =
cv(t) match
case t if t.isEmpty => None
case t => Some(t.init -> t.last)
I was hoping it could infer WrappedString for C but apparently not.
I couldn't get it to take cv: Conversion (without trying hard).
Firstly,
Welcome to Scala 2.13.14 (OpenJDK 64-Bit Server VM, Java 21.0.2).
Type in expressions for evaluation. Or try :help.
scala> val xs = "abcdef": collection.SeqOps[Char, Seq, Seq[Char]]
val xs: scala.collection.SeqOps[Char,Seq,Seq[Char]] = abcdef
scala> xs.getClass
val res0: Class[_ <: scala.collection.SeqOps[Char,Seq,Seq[Char]]] = class scala.collection.immutable.WrappedString
scala> xs match { case head +: tail => tail }
val res1: scala.collection.SeqOps[Char,Seq,Seq[Char]] = bcdef
scala>
Thirdly, for completeness, 2.12 warns
Welcome to Scala 2.12.19 (OpenJDK 64-Bit Server VM, Java 11.0.21).
Type in expressions for evaluation. Or try :help.
scala> import scala.collection.SeqLike
import scala.collection.SeqLike
scala> val xs: SeqLike[Char, String] = "abcdef"
xs: scala.collection.SeqLike[Char,String] = abcdef
scala> xs match { case head +: tail => tail }
<console>:14: warning: abstract type pattern Coll is unchecked since it is eliminated by erasure
xs match { case head +: tail => tail }
^
java.lang.ClassCastException: class java.lang.String cannot be cast to class scala.collection.SeqLike (java.lang.String is in module java.base of loader 'bootstrap'; scala.collection.SeqLike is in unnamed module of loader 'bootstrap')
... 28 elided
scala>
Forgot to mention
Welcome to Scala 2.13.14 (OpenJDK 64-Bit Server VM, Java 21.0.2).
Type in expressions for evaluation. Or try :help.
scala> "abc" match { case x +: y :+ z => y }
^
error: scrutinee is incompatible with pattern type;
found : C with scala.collection.SeqOps[A,CC,C]
required: String
scala> "abc".view match { case x +: y :+ z => y }
^
error: scrutinee is incompatible with pattern type;
found : C with scala.collection.SeqOps[A,CC,C]
required: scala.collection.StringView
scala> "abc".toSeq match { case x +: y :+ z => y }
val res2: scala.collection.immutable.WrappedString = b
scala>
It might be surprising that the view case does not work. I would fail the job interview where they ask to compare StringOps, WrappedString, and StringView.
Also worth adding that x +: y :+ z is "precedence then associativity", where + is higher precedence than :.
x + y +: z is not legal. At the same precedence, it requires same associativity.
Maybe I'm not the only person annoyed that with a longish code block, github doesn't let me drag the corner of the edit box bigger; until I add an empty line.