pattern matcher can still surprise

102 views
Skip to first unread message

Paul Phillips

unread,
Nov 13, 2012, 11:03:33 AM11/13/12
to scala-i...@googlegroups.com
Is it intuitive to anyone that these two lines are not equivalent, and not in a small way? Does it seem desirable that this be the case?

  for (X <- xs) yield X
  xs map { case X => X }

Here we go:

scala> object X
defined module X

scala> val xs = List[Any](1)
xs: List[Any] = List(1)

scala> for (X <- xs) yield X
res1: List[Any] = List(1)

scala> xs map { case X => X }
scala.MatchError: 1 (of class java.lang.Integer)
  at $anonfun$1.apply(<console>:10)
  at $anonfun$1.apply(<console>:10)

But do it this way, and they behave the same!

scala> object X
defined module X

scala> val xs = List[Any]((1, 2))
xs: List[Any] = List((1,2))

scala> for ((X, X) <- xs) yield (X, X)
scala.MatchError: (1,2) (of class scala.Tuple2$mcII$sp)
at $anonfun$1.apply(<console>:10)
at $anonfun$1.apply(<console>:10)

scala> xs foreach { case (X, X) => (X, X) }
scala.MatchError: (1,2) (of class scala.Tuple2$mcII$sp)
at $anonfun$1.apply(<console>:10)
at $anonfun$1.apply(<console>:10)

martin odersky

unread,
Nov 13, 2012, 11:20:10 AM11/13/12
to scala-internals
I think it's a side effect of another symmetry:

Both

  for (X <- xs) yield X
  for (x: Int <- xs) yield x

behave differently from

  xs map { case X => X }
  xs map { case x: Int => x }

but they behave the same as

  val X = expr
  val x: Int = expr

Both for expressions and val definitions behave exactly the same wrt typing, and I think it's a good thing that they do. If we want to align for expressions with map { case ...} then we have to break the alignement with val definitions. Or else turn val definitions into full pattern matches as well. But that would mean:

1) You cannot define

    val N = 10

2) val x: Int = "abc"

breaks at run-time instead of compile-time.

Cheers

 - Martin

--
Martin Odersky
Prof., EPFL and Chairman, Typesafe
PSED, 1015 Lausanne, Switzerland
Tel. EPFL: +41 21 693 6863
Tel. Typesafe: +41 21 691 4967

Paul Phillips

unread,
Nov 13, 2012, 11:58:37 AM11/13/12
to scala-i...@googlegroups.com


On Tue, Nov 13, 2012 at 8:20 AM, martin odersky <martin....@epfl.ch> wrote:
I think it's a side effect of another symmetry:

That makes it seem almost reasonable. It would take a fairly unlucky confluence of events to be burned by it anyway.
Reply all
Reply to author
Forward
0 new messages