As I try to organize things a bit around here, here’s a list of some tutorials I’ve written lately about the Scala collections classes:
Important note about Seq, IndexedSeq, and LinearSeq
As an important note, I use
Seq in the following examples to keep things simple, but in your code you should be more precise and use
LinearSeq where appropriate. As the
Seq class Scaladoc states:
To append or prepend one or more elements to a
Seq, use these methods:
One thing I never thought about before is that if you need to get multiple, unique, random elements from a list of elements, one solution to the problem is to shuffle the list and then take as many elements as you want/need. For instance, if you want three unique, random elements from a list of integers in Scala, you can do this:
scala> val list = List(1,2,3,4,5,1,2,3,4,5) list: List[Int] = List(1, 2, 3, 4, 5, 1, 2, 3, 4, 5) scala> val uniq = list.distinct uniq: List[Int] = List(1, 2, 3, 4, 5) scala> val shuffled = scala.util.Random.shuffle(uniq) shuffled: List[Int] = List(1, 4, 5, 2, 3) scala> val firstThree = shuffled.take(3) firstThree: List[Int] = List(1, 4, 5)
As that solution shows, you start with a simple list; get the unique/distinct elements from the list; shuffle those elements to create a new list; then take the first three elements from the shuffled list. That’s probably not a great solution for huge lists, but for many simple lists it’s a way to get multiple random elements from the list.
Alex Nedelcu has a good article titled, In Defense of OOFP, in which he writes about Scala, OOP, FP, and the Scala collections classes.
As a short note, here’s some Scala source code that shows how to write a
foldLeft function using recursion:
When I wrote the Scala Cookbook, I gave each recipe and then each chapter my full attention. I thought that if I wrote each recipe as well as possible, and included important recipes in each chapter, well, I wanted each chapter to be worth the price of the entire book. That was my goal.
As a result of this effort -- and perhaps to the chagrin of my editor -- the Scala collections chapters ended up being 130 pages in length.