Reputation: 521
i got a problem in Scala's loop: in java i can do this:
for(int i=1;i<list.length;i=i*2
but how could i do the same in scala? Scala's for index cannot change
Upvotes: 1
Views: 347
Reputation: 1239
scanLeft
method might be helpful there:
def exps(n: Int, p: Int) = (0 until n).scanLeft(1)((acc, _) => acc * p)
val list = List(2, 3, 5, 7)
for (i <- exps(list.size, 2)) println(i)
1
2
4
8
16
Or using infinite streams:
def expStream(p: Int, i: Int = 1): Stream[Int] = i #:: expStream(p, i * p)
for (i <- expStream(2).take(list.size)) println(i)
Also you can use Stream.iterate
(which is somewhat more concise) as Gyro Gearless has suggested in their answer:
def expStream(p: Int) = Stream.iterate(1)(_ * p)
Upvotes: 4
Reputation: 5279
An idiomatic way would be to create an Stream from the function "*2":
import Stream._
val potsOfTwo = Stream.iterate (1) (_ * 2).takeWhile (_ < 1000)
potsOfTwo.foreach { println _ }
scala> potsOfTwo.foreach { println _ } 1 2 4 8 16 32 64 128 256 512
Upvotes: 3
Reputation: 1539
Well. On practice I would probably go for next solution:
val m = 100
val r = (0 to m).map(x => if (x * 2 < m) x * 2 else -1).filter(t => t != -1 )
println(r)
Here is documentation and examples you need to look at. I would suspect you looking for ranges:
val r = 1 to 10
r: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5,
6, 7, 8, 9, 10)
scala> val r = 1 to 10 by 2
r: scala.collection.immutable.Range = Range(1, 3, 5, 7, 9)
scala> val r = 1 to 10 by 3
r: scala.collection.immutable.Range = Range(1, 4, 7, 10)
http://docs.scala-lang.org/tutorials/tour/sequence-comprehensions.html
https://www.safaribooksonline.com/library/view/scala-cookbook/9781449340292/ch02s09.html
Upvotes: 0