Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it make any sense to use pattern matching in Scala with really simple cases?

In 'Programming in Scala, Second Edition' at page 410 you can find class Simulation which have the following method:

private def next() {
  (agenda: @unchecked) match {
    case item :: rest =>
      agenda = rest
      curtime = item.time
      item.action()
  }
}

I'm curious why Odersky implemented this with pattern matching rather than just like that:

private def next() {
  val item = agenda.head
  agenda = agenda.tail
  curtime = item.time
  item.action()
}

Is pattern matching so efficient that it doesn't matter at all? Or it was just not so perfect example?

like image 500
Piotr Kukielka Avatar asked Dec 26 '11 18:12

Piotr Kukielka


2 Answers

Normally I'd write it the way you did. (Even though pattern matching is quite efficient, it is not as efficient as head/tail.) You'd use pattern matching if

  1. You wanted to practice pattern matching
  2. You wanted a MatchException instead of a NoSuchElementException
  3. You were going to fill in other cases later.
like image 152
Rex Kerr Avatar answered Sep 19 '22 10:09

Rex Kerr


There are a couple reasons:

  1. Part of the point of the book is to get you thinking in Scala (functional) terms; pattern matching is the functional-programming equivalent.

  2. Pattern matching and the functional approach are the natural pattern in Scala, and allow things like concurrency in a natural way; learn that pattern and your Scala programs will be ready for more advanced uses.

like image 43
Charlie Martin Avatar answered Sep 20 '22 10:09

Charlie Martin