Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how this code is working?

 
Pankaj Mittal
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 !!
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15369
40
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Stefan Wagner
Ranch Hand
Posts: 1923
Linux Postgres Database Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see odd integers returned, not primes, and would prefer a filter instead:

 
Pankaj Mittal
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys !!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic