Rewrite the 'for' loop from Java to Scala

I need to convert Java code to Scala. I have such a source. How to rewrite it in Scala? The question may be simple. But this is more suitable for (i <- 1 to 10) {} examples in the documentation.

for (int i = password.length(); i != 0; i >>>=1) { some code } 

Tsar refers, Alex

+4
source share
4 answers

If you want it to be as fast as possible, which I assume is the case where the shift operation is then you should use a while loop:

 var i = password.length() while (i != 0) { // some code i >>>= 1 } 

This is one of the few cases where Java is more compact than Scala with the same operation.

You can also use tail recursion:

 final def passwordStuff(password: Password)(i: Int = password.length): Whatever = { if (i != 0) { // Some code passwordStuff(password)(i >>> 1) } } 

which will compile into something at the same speed as the while loop (anyway, anyway).

+6
source

If you are looking for an exotic functional way, you can write something like this:

 Stream.iterate(password.length)(i => i >>> 1).takeWhile(0!=) 

He lazily performs the following actions: takes the password length as the initial value, applies { => i >>> 1 } , passes it to the next iteration, applies ... pass, ...

Then I calculate the scope, restricting it to only values ​​that are not equal to 0.

+2
source

i >>>= 1 is equivalent to i /= 2 for positive integers.

Combining this knowledge with the answers to the for loop increment (loop variable) in scala at power 5 , you should be set.

+1
source

did not know the operator β†’> =. Let's try to be a little more functional, foreach takes the function A => Unit, in which case A is Int

 def breakdownBy2(from:Int):List[Int] = if(from == 0) Nil else List(from) ++ breakdownBy2(from/2) breakdownBy2(passoword.length).foreach(println(_)) 
0
source

Source: https://habr.com/ru/post/1411396/


All Articles