Trying to get a handle on pattern matching here– coming from a C++/Java background it’s very foreign to me.
The point of this branch is to check each member of a List d of tuples [format of (string,object). I want to define three cases.
1) If the counter in this function is larger than the size of the list (defined in another called acc), I want to return nothing (because there is no match)
2) If the key given in the input matches a tuple in the list, I want to return its value (or, whatever is stored in the tuple._2).
3) If there is no match, and there is still more list to iterate, increment and continue.
My code is below:
def get(key:String):Option[Any] = {
var counter: Int = 0
val flag: Boolean = false
x match {
case (counter > acc) => None
case ((d(counter)._1) == key) => d(counter)._2
case _ => counter += 1
}
My issue here is while the first case seems to compile correctly, the second throws an error:
:36: error: ')' expected but '.' found.
case ((d(counter)._1) == key) => d(counter)._2
The third as well:
scala> case _ => counter += 1 :1: error: illegal start of definition
But I assume it’s because the second isn’t correct. My first thought is that I’m not comparing tuples correctly, but I seem to be following the syntax for indexing into a tuple, so I’m stumped. Can anyone steer me in the right direction?
Hopefully a few things to clear up your confusion:
Matching in scala follows this general template:
It looks like you may have attempted to use the match/case expression as more of an if/else if/else kind of block, and as far as I can tell, the
xdoesn’t really matter within said block. If that’s the case, you might be fine with something likeBUT
Some info on
Lists in scala. You should always think of it like aLinkedList, where indexed lookup is anO(n)operation. Lists can be matched with ahead :: tailformat, andNilis an empty list. For example:It looks like you’re constructing a kind of ListMap, so I’ll write up a more “functional”/”recursive” way of implementing your
getmethod.I’ll assume that
dis the backing list, of typeList[(String, Any)]The three case statements can be explained as follows:
1) The first element in
listis a tuple of(k, value). The rest of the list is matched to the_because we don’t care about it in this case. The condition asks ifkis equal to the key we are looking for. In this case, we want to return thevaluefrom the tuple.2) Since the first element didn’t have the right key, we want to recurse. We don’t care about the first element, but we want the rest of the list so that we can recurse with it.
3)
case Nilmeans there’s nothing in the list, which should mark “failure” and the end of the recursion. In this case we returnNone. Consider this the same as yourcounter > acccondition from your question.Please don’t hesitate to ask for further explanation; and if I’ve accidentally made a mistake (won’t compile, etc), point it out and I will fix it.