Reputation: 53786
I'm attempting to convert a Selection sort from Java to Scala and im unsure how to convert this loop to Scala :
for (int j = i + 1; j < N; j++)
Here is a larger Java code sample and its Scala equivalent :
Java :
sort(Comparable[] a)
{
int N = a.length;
for (int i = 0; i < N; i++)
{
int min = i
for (int j = i + 1; j < N; j++)
}
Scala :
def sort(a : Array[Ordered[Any]]) = {
var N = a.length
for (i <- 0 until N) {
var min = i
for(j <- until j < N){
}
}
}
How do I convert the inner loop to Scala ?
for (int j = i + 1; j < N; j++)
I dont know how to do assignment while iterating...
Upvotes: 3
Views: 3143
Reputation: 2345
Using for loops (not exactly a functional/idiomatic scala way) for iterating will closely resemble the java code. This will get you through.
def sort(a: Array[Comparable]) {
val N = a.length
for (
i <- 0 until N;
min = i;
j <- (i + 1) until N
) {
// more code..
}
}
Here's your java code for reference:
sort(Comparable[] a)
{
int N = a.length;
for (int i = 0; i < N; i++)
{
int min = i
for (int j = i + 1; j < N; j++)
}
Upvotes: 0
Reputation: 16907
Unfortunately, the standard for loops are quite slow on Scala (especially with older version).
An alternative is the classical while loop, even if it is not so clear:
def sort(a : Array[Ordered[Any]]) = {
val N = a.length
var i = 0;
while (i < N) {
var min = i
var j = i + 1;
while (j < N) {
j += 1;
}
i += 1;
}
}
Or tail recursive functions:
def sort(a : Array[Ordered[Any]]) = {
val N = a.length
def l1(i: Int){
def l2(j: Int, min: Int){
if (j < N)
l2(j+1, min)
}
if (i < N) {
l2(i+1, i);
l1(i+1);
}
}
}
Or the cfor of spire:
def sort(a : Array[Ordered[Any]]) = {
val N = a.length
cfor(0)(_ < N, _ + 1) { i =>
var min = i
cfor(i+1)(_ < N, _ + 1) { j =>
}
}
}
Upvotes: 3
Reputation: 62835
Here you go:
def sort(a : Array[Ordered[Any]]) = {
val N = a.length
for (i <- 0 until N) {
var min = i
for(j <- i + 1 until N){
}
}
}
Moreover, in Scala you can define values inside for comprehension, and merge multiple blocks into one:
def sort(a : Array[Ordered[Any]]) = {
val n = a.length
for(i <- 0 until n; min = i; j <- i + 1 until n) { // min here is val, not var
// do something with i, j and min
}
}
Sometimes, this may lead to cleaner code
Upvotes: 7