43

I have a function:

def func(a: int, b: int, c: double): int

And I want to match various possible scenarios

  1. Wherever c is 0, return b-a
  2. Wherever c > 9, return 0
  3. Wherever a=b return 0

And so on, before doing some more complex logic if none of the above are satisfied.

Do I have to match c separately first, or can I match on a,b,c, like _,_,0?

Phil H
  • 19,928
  • 7
  • 68
  • 105

2 Answers2

78

You can pattern match all described cases like this:

def func(a: Int, b: Int, c: Double) = (a, b, c) match {
    case (a, b, 0) => b - a
    case (a, b, c) if c > 9 || a == b => 0
    case _ => 1 // add your logic here
}
Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
tenshi
  • 26,268
  • 8
  • 76
  • 90
  • 2
    This does indeed answer the question as posed, but why use patten matching here? It seems a case where the good old if statement works just fine.. – The Archetypal Paul Mar 22 '11 at 16:49
  • 1
    @Paul if you have many conditions, each with an action to take, and of which a single condition will be matched, then that's what pattern matching was made for. See Lisp's `cond`. – Daniel C. Sobral Mar 22 '11 at 20:00
  • 1
    @Paul: To make long story short - it makes code more declarative IMHO. I like declarative code and programming in general. I saw in many other languages features, that allow them make pattern match (like above) directly in argument list - you can find it in Haskell, Clojure, Prolog for example. I wanted the same feature in Scala until I realized, that we already have it, but in other form (example is in my answer). I find this form very useful - it makes my code more expressive, easy to understand and maintain (IMHO). – tenshi Mar 22 '11 at 20:27
  • 2
    I'm not arguing that pattern matching isn't valuable anywhere. I am arguing that here it doesn't help make things clearer - mostly because all values used by any condition need to be in the expression matched (and Lisp's COND is not pattern matching, it's just if elseif else in a different wrapper. Here I would claim if/else if / else if / else is clearer - and more like COND) – The Archetypal Paul Mar 22 '11 at 20:38
  • Also, pattern matching (in Scala) introduces unnecessary overhead when if whould be sufficient (i.e. the calls to `unapply`). – Raphael Mar 24 '11 at 00:43
5

Following on from my comments to Easy Angel's answer, I still feel this

if (c == 0)
   b -a
else if (c > 9)
   0
else if (a == b)
   0
else 
   1 // your logic here

is clearer. Basically because there isn't really any pattern to match here.

The Archetypal Paul
  • 41,321
  • 20
  • 104
  • 134