9

In ML, one can assign names for each element of a matched pattern:

fun findPair n nil = NONE
| findPair n (head as (n1, _))::rest =
    if n = n1 then (SOME head) else (findPair n rest)

In this code, I defined an alias for the first pair of the list and matched the contents of the pair. Is there an equivalent construct in Scala?

Blaisorblade
  • 6,438
  • 1
  • 43
  • 76
Evan Kroske
  • 4,506
  • 12
  • 40
  • 59

2 Answers2

14

You can do variable binding with the @ symbol, e.g.:

scala> val wholeList @ List(x, _*) = List(1,2,3)
wholeList: List[Int] = List(1, 2, 3)
x: Int = 1
DaoWen
  • 32,589
  • 6
  • 74
  • 101
0

I'm sure you'll get a more complete answer later as I'm not sure how to write it recursively like your example, but maybe this variation would work for you:

scala> val pairs = List((1, "a"), (2, "b"), (3, "c"))
pairs: List[(Int, String)] = List((1,a), (2,b), (3,c))

scala> val n = 2
n: Int = 2

scala> pairs find {e => e._1 == n}
res0: Option[(Int, String)] = Some((2,b))

OK, next attempt at direct translation. How about this?

scala> def findPair[A, B](n: A, p: List[Tuple2[A, B]]): Option[Tuple2[A, B]] = p match {
     | case Nil => None
     | case head::rest if head._1 == n => Some(head)
     | case _::rest => findPair(n, rest)
     | }
findPair: [A, B](n: A, p: List[(A, B)])Option[(A, B)]
Dave L.
  • 9,595
  • 7
  • 43
  • 69
  • The code I posted was just an example to demonstrate the behavior of the operator I'm looking for. I'm interested in whether the "as" operator exists in Scala in some form. – Evan Kroske Nov 03 '12 at 04:13
  • I appreciate the effort, but I really don't care about the little algorithm I posted. The point was to rename match variables. I edited your answer to answer my own question. I'll upvote the answer once my edit goes through. – Evan Kroske Nov 03 '12 at 05:05