tags:

views:

1286

answers:

5

Hello,

I've recently been working on a beginner's project in Scala, and have a beginner question about Scala's Lists.

Say I have a list of tuples ( List[Tuple2[String, String]], for example). Is there a convenience method to return the first occurence of a specified tuple from the List, or is it necessary to iterate through the list by hand?

+3  A: 

You could try using find.

Tim Sullivan
+2  A: 

If you're learning scala, I'd take a good look at the Seq trait. It provides the basis for much of scala's functional goodness.

sblundy
+3  A: 
binil
+3  A: 

As mentioned in a previous comment, find is probably the easiest way to do this. There are actually three different "linear search" methods in Scala's collections, each returning a slightly different value. Which one you use depends upon what you need the data for. For example, do you need an index, or do you just need a boolean true/false?

Daniel Spiewak
A: 

You could also do this, which doesn't require knowing the field names in the Tuple2 class--it uses pattern matching instead:

list find { case (x,y,_) => x == "C" && y == "D" }

"find" is good when you know you only need one; if you want to find all matching elements you could either use "filter" or the equivalent sugary for comprehension:

for ( (x,y,z) <- list if x == "C" && y == "D") yield (x,y,z)