I am trying to learn Scala, so can anyone tell me how to convert the following in scala:
for (int t = 0; true; t++)
Thank you in advance.
With imperative style you can write (as you do in Java):
var t = 0
while(true) {
t+=1
...
}
With lazy functional this could be:
def ints(n: Int = 0): Stream[Int] = Stream.cons(n, ints(n+1))
ints().map(t => ...)
Using built-in functions:
Iterator.from(0).map ( t => .... )
The common use case with such infinite structures, is to take infinite stream or iterator, perform some operations on it, and then take number of results:
Iterator.from(0).filter(t => t % 1 == 0).map(t => t*t).take(10).toList
++ method on Int in Scala, you should write t += 1 instead of t++.foreach instead of map, since the latter creates a new collection, so will eat memory particularly if what you're doing is infinite, i.e. Iterator from 0 foreach { t => ... }.As I mentioned in the comments, your question does not seem to make much sense - please add more detail.
For now, the closest Scala translation I can come up with would be:
Stream from 0
while (true) :)You can use while or for.
You can use for
for(i<-0 to 100) {
println(i)
}
or you use until when you want to increment by N number
for(i <- 5 until 55 by 5) {
println(i)
}
or you better use while
var i = 0
while(true) {
...
i+=1
}
or also do-while
var i = 0
do {
...
i += 1
} while(true)
Have a look at : http://www.simplyscala.com/ and test it out by yourself
Also, in my blog I did some posts about imperative scala where I used for and while loops you can have a look there.
A simple for comprehension in scala looks mostly this way:
for (i <- 0 until 10) {
// do some stuff
}
for loops.yield as "for-loops", so it seems they were intended to be used as such.)
tupwards, starting from zero. But you left out the body of the loop. What is your loop supposed to do? When will it stop?