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,") }
Related
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++);
I had a cycle for counter:
List<Mt4Report> history = ...
int counter = 0;
for (Mt4Report item : history) {
if (item.getProfit().compareTo(BigDecimal.ZERO) < 0) {
counter++;
} else {
break;
}
}
How I can write the same idea with lambda expression something .findFirst().ifPresent but withholding break statement?
With Java-9 and above, you can use takeWhile approach as :
int counter = (int) history.stream()
.takeWhile(item -> item.getProfit().compareTo(BigDecimal.ZERO) < 0)
.count();
For the Java-8 solution, you can look into a custom implementation of takeWhile provided in this answer. On the other hand, a less efficient implementation with the use of indexOf could be to perform:
int count = history.stream()
.filter(ite -> ite.getProfit().compareTo(BigDecimal.ZERO) >= 0)
.findFirst()
.map(history::indexOf)
.orElse(history.size());
As Holger suggested to improve the above solution, you can make use of the IntStream with findFirst:
int count = IntStream.range(0, history.size())
.filter(ix -> history.get(ix).getProfit() .compareTo(BigDecimal.ZERO) >= 0)
.findFirst()
.orElse(history.size());
As per Java 8 there is no direct solution for this problem, which is basically stopping a Stream using a Predicate.
In Java 9 you have the takeWhile() method but in Java 8, there is no such thing like that.
Please refer to this post
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;
}
}
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
}
simonn helped me to code an ordered integer partition function here. He posted two functions: one function simply gives back the count of partitions, the second function gives the partitions as a list.
I've already managed to translate the first function from Java to PHP:
Java version
PHP version
Unfortunately, I can't manage to translate the second function. Can anyone help me and translate this small function for me?
public class Partitions2
{
private static void showPartitions(int sizeSet, int numPartitions)
{
showPartitions("", 0, sizeSet, numPartitions);
}
private static void showPartitions(String prefix, int start, int finish,
int numLeft)
{
if (numLeft == 0 && start == finish) {
System.out.println(prefix);
} else {
prefix += "|";
for (int i = start + 1; i <= finish; i++) {
prefix += i + ",";
showPartitions(prefix, i, finish, numLeft - 1);
}
}
}
public static void main(String[] args)
{
showPartitions(5, 3);
}
}
It would be great if the solution would be one single function instead of a class with several functions.
Thank you very much in advance! And thanks again to simonn for this great answer!
You probably don't need the main method, that just seems to be a test rig showing how to invoke the other method.
The problem mapping this code directly to PHP is that you can't overload method names in PHP. Instead you should concentrate on translating the second version of the showPartitions function. If you need a 2-argument version you can use default values for the prefix and start parameters (you'll have to change the parameter order to do this because in PHP optional parameters must come last).
Here's my (untested) attempt at translating the most important function:
function showPartitions($prefix, $start, $finish, $numLeft)
{
if ($numLeft == 0 && $start == $finish) {
echo $prefix."\n";
} else {
$prefix .= "|";
for ($i = $start + 1; $i <= $finish; $i++) {
$prefix .= $i.",";
showPartitions($prefix, $i, $finish, $numLeft - 1);
}
}
}