This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Scala and the fly likes how this code is working? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Languages » Scala
Bookmark "how this code is working?" Watch "how this code is working?" New topic
Author

how this code is working?

Pankaj Mittal
Ranch Hand

Joined: Jul 09, 2008
Posts: 32
Hii guys !!

I'm very new to Scala and going through some tutorials and one of them I found this code


I know it is returning list of prime integers but I couldn't know how this folder is working...can somebody help me??

Thanks in advance !!


2008 SCJP(5.0) 88%
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

The operator /: is the fold left operator. It is applied here on an empty list of Int and lst.

The thing on the right side is a function literal, that takes two parameters x and y and returns what the if-statement evaluates into, which is x if y is even, and x + y if y is odd.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
The code you're looking at isn't returning a list of prime integers.

Building on what Jesper wrote, Ill try to translate the code into Java for you:



As an aside, stylistically, I really dislike /: and :\, I much prefer the foldLeft and foldRight.



However, you must remember that foldRight is not tail-recursive and can blow the stack for large lists.


Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Stefan Wagner
Ranch Hand

Joined: Jun 02, 2003
Posts: 1923

I see odd integers returned, not primes, and would prefer a filter instead:



http://home.arcor.de/hirnstrom/bewerbung
Pankaj Mittal
Ranch Hand

Joined: Jul 09, 2008
Posts: 32
Thanks guys !!!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: how this code is working?
 
Similar Threads
Sudoku solver help (not brute force)
abstract class instantiation
Using java object in LHS of a Jess rule failed
how to compare the values in arrays
I am new to Java programming