Help coderanch get a
new server
by contributing to the fundraiser
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Jeanne Boyarsky
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Rob Spoor
• Devaka Cooray
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Tim Moores
Bartenders:
• Mikalai Zaikin

how this code is working?

Ranch Hand
Posts: 32
• Number of slices to send:
Optional 'thank-you' note:
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??

Java Cowboy
Posts: 16084
88
• Number of slices to send:
Optional 'thank-you' note:
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.

Ranch Hand
Posts: 1296
• Number of slices to send:
Optional 'thank-you' note:
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.

Ranch Hand
Posts: 1923
• Number of slices to send:
Optional 'thank-you' note:
I see odd integers returned, not primes, and would prefer a filter instead:

Pankaj Mittal
Ranch Hand
Posts: 32
• Number of slices to send:
Optional 'thank-you' note:
Thanks guys !!!

 Willie Smits can speak 40 languages. This tiny ad can speak only one: We need your help - Coderanch server fundraiser https://coderanch.com/t/782867/Coderanch-server-fundraiser