blue-sky blue-sky - 1 year ago 158
Scala Question

Get list of elements that are divisible by 3 or 5 from 1 - 1000

I'm trying to write a functional approach in scala to get a list of all numbers between 1 & 1000 that are divisible by 3 or 5

Here is what I have so far :

def getListOfElements(): List[Int] = {
val list = List()

for (i <- 0 until 1000) {
//list.
}
list match {
case Nil => 0
}
list
}


The for loop seems like an imperative approach and I'm not sure what to match on in the case class. Some guidance please ?

Answer Source

Here's how I would do it with a for expression.

for( i <- 1 to 1000 if i % 3 == 0 || i % 5 == 0) yield i

This gives:

 scala.collection.immutable.IndexedSeq[Int] = Vector(3, 5, 6, 9, 10, 12, 15, 18, 20, 21...

Here's another approach filtering on a Range of numbers.

scala> 1 to 1000
res0: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10...


scala> res0.filter(x => x % 3 == 0 || x % 5 == 0)
res1: scala.collection.immutable.IndexedSeq[Int] = Vector(3, 5, 6, 9, 10, 12, 15, 18, 20, 21...

If you really want a List on the return value use toList. e.g. res0.toList.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download