FOR, WHILE Is Too Easy, Let’s Go Looping

Caoyuan Blog - - October 22, 2008

With several 10k code in Erlang, I’m familiar with functional style coding, and I found I can almost rewrite any functions in Erlang to Scala, in syntax meaning.

Now, I have some piece of code written in Java, which I need to translate them to Scala. Since “for”, “while”, or “do” statement is so easy in Java, I can find a lot of them in Java code. The problem is, should I keep them in the corresponding “for”, “while”, “do” in Scala, or, as what I do in Erlang, use recursive function call, or, “loop”?

I sure choose to loop, and since Scala supports recursive function call on functions defined in function body (Erlang doesn’t), I choose define these functions’ name as “loop”, and I tried to write code let “loop” looks like a replacement of “for”, “while” etc.

Here’s a piece of code that is used to read number string and convert to double, only piece of them.

The Java code:

public class ReadNum { private double readNumber(int fstChar, boolean isNeg) { StringBuilder out = new StringBuilder(22); out.append(fstChar); double v = '0' - fstChar; // the maxima length of number stirng won't exceed 22 for (int i = 0; i < 22; i++) { int c = getChar(); switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': v = v * 10 - (c - '0'); out.append(c); continue; case '.': out.append('.'); return readFrac(out, 22 - i); case 'e': case 'E': out.append(c); return readExp(out, 22 - i); default: if (c != -1) backup(1); if (!isNeg) return v; else return -v } } return 0; }
}

The Scala code:

class ReadNum { private def readNumber(fstChar:Char, isNeg:Boolean) :Double = { val out = new StringBuilder(22) out.append(fstChar) val v:Double = '0' - fstChar def loop(c:Char, v:Double, i:Int) :Double = c match { // the maxima length of number stirng won't exceed 22 case _ if i > 21 => 0 case '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' => out.append(c) val v1 = v * 10 - (c - '0') loop(getChar, v1, i + 1) case '.' => out.append('.') readFrac(out, 22 - i) case 'e' | 'E' => out.append(c) readExp(out, 22 - i) case _ => if (c != -1) backup(1) if (isNeg) v else -v }; loop(getChar, v, 1) }
}

As you can see in line 25, the loop call is put at the position immediately after the “loop” definition, following “}; “, I don’t put it to another new line, it makes me aware of the “loop” function is just used for this call.

And yes, I named all these embedded looping function as “loop”, every where.



Categories: Blogs  Caoyuan Blog  

Comments

No comments so far, you could be the first.

Add comment

Name:

Email:

URL:

Smileys

Remember my personal information

Notify me of follow-up comments?