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 :
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
.