1. Indexes of a collection
If you want to traverse a list of elements keeping the index in mind, you could do this with a fold but a more elegant way is something like:
val words = List("the", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog")
words.zipWithIndex // returns tuples like (word, index)
2. Choosing only some elements of a collection
Now, let's say we want the tuples of those words that begin with 't'. We do this with the collect function in TraversableLike.
words.zipWithIndex collect {
case (word, index) if word.startsWith("t") => (word, index)
}
List((the,0), (the,6))
3. Counting the elements that meet a criteria
is very simple:
words count (_ startsWith("t"))
Will, unsurprisingly, return 2 for the above collection.
What I learned this week is that you could do all these with folds etc but Scala (I am told) has methods that do pretty much anything you could want. It's just a matter of learning them.
No comments:
Post a Comment