aspose file tools*
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
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: 14157
    
  19

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 !!!
 
 
subject: how this code is working?