Converting Java to Scala - java

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

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

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.
http://carlosqt.blogspot.com/search/label/Scala

A simple for comprehension in scala looks mostly this way:
for (i <- 0 until 10) {
// do some stuff
}

Related

Does Java 8 provide a good way to repeat a function based on specific condition?

I am having the old style while loop like below:
int i = 1, n = 5;
while(i <= n) {
if (doSomething()) {
break;
}
i++;
}
Is it possible to do it in a good way in Java 8?
You can do it using IntStream and findFirst short-circuiting terminal operation. And when ever doSomething() method returns true the execution of stream pipeline will be terminated
IntStream.range(1,5)
.filter(i -> doSomething())
.findFirst();
Even though you have mentioned Java 8, if you are going to use Java 9 or above and need to know the number of times the loop was executed, then do as follows:
long count = IntStream.range(1,6)
.takeWhile(i -> !doSomething()) // loop continued till doSomething is true
.count();
takeWhile was introduced in Java 9.
Plain old approach:
while(i <= n && !doSomething()) {
// do something here
i++;
}
Pretty clear and concise.
This is tidier:
for (int i = 0; i < 5 && !doSomething(); i++);

Kotlin loop with irregular steps

I have been trying to translate a Java for expression into Kotlin which produces this sequence:
1,2,4,8,16,32,64
This is the Java code:
for(int i = 1; i < 100; i = i + i) {
System.out.printf("%d,", i);
}
The only way I have found to translate this into Kotlin is:
var i = 1
while (i < 100) {
print("$i,")
i += i
}
I have tried to use step expressions, but this does not seem to work. Is there any way to express this type of sequence more elegantly in Kotlin?
I know you can have code like this one using Kotlin + Java 9:
Stream.iterate(1, { it <= 100 }) { it!! + it }.forEach { print("$it,") }
But this relies on Java libraries and I would prefer Kotlin native libraries.
You can use the generateSequence function to create an infinite sequence, then use takeWhile to limit it at a specific value and then use forEach instead of a for-in construct to handle each iteration:
generateSequence(1) { it + it }.takeWhile { it < 100 }.forEach { print("$it,") }

conditional conditions in Java

I have:
boolean cond=false;
if(!gto)
cond=(in-Math.pow(base, pot)<0);
else
cond=(in-Math.pow(base, pot)>=0);
while(cond)//Pos1
...
This work not in the desired way, because pot is changed within the while-loop.
Of coure I could write a boolean-valued method, but I wonder, if there is a way to force Java to evaluate cond just when reaching Pos1?
while((in-Math.pow(base,pot<0&&!gto)||(in-Math.pow(base, pot)>=0&&gto))){
//do sth
}
is this what you want?
For cleanliness and maintainability, use a method, assuming you have Java 8 available, you could also use a lambda predicate as shown below:
Predicate<Boolean> checkCondition = (boolean gto) -> {
double someCalculationResult = in - Math.pow(base, pot);
if (!gto) {
return someCalculationResult < 0;
}
return someCalculationResult >= 0;
}
while (checkCondition(gto)) {
...
}
Or inline the condition (see answer by #kleopi) if this is some write and forget about it code.
If the value of gto does not change in the loop and the loop body is not complex, then you could just write two separate loops for the individual cases:
if ( gto ) {
while ( in - Math.pow(base, pot) >= 0 ) {
// Do stuff
}
} else {
while ( in - Math.pow(base, pot) < 0 ) {
// Do stuff
}
}
If possible, you could then also move the loop body into a separate method and call it from both loops.

Lazy fibonnaci series

I have just started learning haskell and wondering if there is any way we can implement below fibonacci series in C# or java or other non-lazy imperative languages.
In haskell we can succinctly generate fibonacci series with the below one liner
fibonacci = 0 : 1 : zipWith (+) fibonacci (tail fibonacci)
Question - I understand that as C#/Java etc eagerly evaluates, the above would probably go to an infinite loop. But what i do not understand is that even if we use a thunk, how can we can create a self referencing data structure which changes as we iterate over it (using recursion).
Appreciate if you could share some snippet
The Scala API docs for Stream contains an example on how to do this in Scala:
val fibs: Stream[BigInt] = BigInt(0) #:: BigInt(1) #:: fibs.zip(fibs.tail).map { n => n._1 + n._2 }
Edit: To implement memoization in a language which doesn't have it built-in like Haskell, you would obviously need to use mutation (an array or a map). For example:
val fib: Int => Int = {
val m = ArrayBuffer(0, 1)
x => if (x < m.size) m(x) else {
println("Calculating " + x + "...")
val r = fib(x - 2) + fib(x - 1)
m += r
r
}
}
This can still be considered to be a pure function as there are no observable side effects (besides runtime performance) in a single threaded environment.
In C# you can implement this in the next way:
IEnumerable <int> Fibonacci() {
var a = 0;
var b = 1;
while (true) {
var t = b;
yield return b = a + b;
a = t;
}
}

Java: set value and check condition at same time

(In the process of writing my original question, I answered it, but the information might be useful to others, and I thought of a new question)
For instance:
int x;
if (x = 5) { ... }
Creates an error:
Type mismatch: cannot convert from int to boolean. (Because assignment doesn't return a
boolean value)
However,
int x;
if ((x = 5) == 5) {
System.out.println("hi!");
}
will print out "hi!"
And similarly,
String myString = "";
if ((myString = "cheese").equals("cheese")) {
System.out.println(myString);
}
prints out "cheese"
Sadly,
if ((int x = 5) > 2) { ... }
does not work with an in-line declaration. How come? Can I get around this?
Sadly,
I suspect that most Java developers would heartily disagree with that sentiment ...
if ((int x = 5) > 2) { ... }
does not work with an in-line
declaration. How come?
It does not work because a declaration is not a Java expression, and cannot be used in an Java expression.
Why did the Java designers not allow this? I suspect that it is a combination of the following:
Java's syntactic origins are c and C++, and you cannot do this in C or C++ either,
this would make the Java grammar more complicated and the syntax harder to understand,
this would make it easier to write obscure / cryptic programs in Java, which goes against the design goals, and
it is unnecessary, since you can trivially do the same thing in simpler ways. For instance, your example can be rewriten this to make the declaration of x to a separate statement.
Can I get around this?
Not without declaring x in a preceding statement; see above.
(For what it is worth, most Java developers avoid using assignments as expressions. You rarely see code like this:
int x = ...;
...
if ((x = computation()) > 2) {
...
}
Java culture is to favour clear / simple code over clever hacks aimed at expressing something in the smallest number of lines of code.)
Your x only exists within the scope of the assignment, so it's already gone by the time you get to > 2. What is the point of this anyway? Are you trying to write deliberately unreadable code?
Your best way to get around this is to declare x in a scope that will remain valid throughout the if statement. Seriously though, I fail to understand what you're doing here. Why are you creating a variable that is supposed to disappear again immediately?
if ((int x = 5) > 2) { ... }
Yes this will not compile because you can't declare variables inside the condition section of if clause
The > test will work fine, as long as you declare the int outside of the if condition. Perhaps you are simplifying your condition for the sake of brevity, but there is no reason to put your declaration in the condition.
Can I get around this?
Yes, declare your var outside the condition.
Because you didn't declare the int separately as you did in the == test.
jcomeau#intrepid:/tmp$ cat /tmp/test.java
class test {
public static void main(String[] args) {
int x;
if ((x = 5) > 2) System.out.println("OK");
}
}
In Java, for() allows initialization code, but if() doesn't.
You can't declare the variable in condition section. For example
for(int i = 0; j < 9; i++){...}
is completely valid statement. Notice we declare the variable in for but not in a condition clause, now look at this,
for(int i = 0; (int j = 0)<9; i++){...} // Don't try to make logical sense out of it
not allowed.

Categories