Basic Scala for loop Issue - scala

I am trying to learn scala, here I am using basic for loop, but I am getting errors while compiling.
object App {
def main(args: Array[String]) {
for (i <- 1 to 10; i % 2 == 0)
Console.println("Counting " + i)
}
}
Errors while compiling :
fortest.scala:5: error: '<-' expected but ')' found.
for (i <- 1 to 10; i % 2 == 0)
^
fortest.scala:7: error: illegal start of simple expression
}
^
two errors found
I am using scala version 2.9.1
Any idea what is the problem..............?

for (i <- 1 to 10 if i % 2 == 0)
println("Counting " + i)

Scala is not Java, thus you cannot use a regular Java syntax. Instead you have to do:
for{
i <- 1 to 10
if(i % 2 == 0)
}{println("Counting " + i)}
or with ; delimeters, inside the (,) parentheses:
for(i <- 1 to 10;if(i % 2 == 0)){
println("Counting " + i)
}
Also, note that Scala's for expressions, have some pretty nifty capabilities.
you can use a for expression with multiple "loop iterators" and conditions.
For instance, instead of writing:
for(i <- 1 to n; if(someCondition(i)){
for(j <- 1 to m; if(otherCondition(j)){
//Do something
}
}
You can simply write:
for{
i <- 1 to n
if(someCondition(i))
j <- 1 to m
if(otherCondition(j))
}{
//Do something
}
SIDE NOTE:
When you extend App (there's a trait of that name in Predef), you don't need to define a main method. You can simply write your code between the curly braces of object:
object MyClazz extends App {
for(i <- 1 to 10;if(i % 2 == 0)){
println("Counting " + i)
}
}

Take a look at the "by" method of the Range class to count by 2
object App {
def main(args: Array[String]) {
for (i <- 2 to 10 by 2)
Console.println("Counting " + i)
}
}
Or, like others have already stated you can fix your loop by doing
object App {
def main(args: Array[String]) {
for {
i <- 1 to 10
if i % 2 == 0
}
Console.println("Counting " + i)
}
}
Or another way:
object App {
def main(args: Array[String]) {
val evenNumbers = for {
i <- 1 to 10
if i % 2 == 0
} yield i
Console.println(evenNumbers.mkString("\n"))
}
}

The modulo 2 condition can be moved to an if clause.
object App {
def main(args: Array[String]) {
for (i <- 1 to 10)
if(i % 2 == 0)
Console.println("Counting " + i)
}
}

Here is the simply example;
for (i <- List(1, 2, 3) if i < 2) println(i)
The best way to exam your code is to use scala shell.

Basically, you are trying to use for-loop + iterator gaurd. Please find below syntax
for ( i <- 1 to 10 if (i%2==0) ) yield i

Related

illegal start of simple pattern about for expression in scala

object main {
def main(args: Array[String]): Unit = {
for (
i <- 1 to 10
if i % 2 == 0;
j <- 2 to 8
if j % 2 == 1;
) {
println(s"i: ${i}, j: ${j}")
val t = i + j
println(s"t: ${t}")
}
}
}
Compiler complains: illegal start of simple pattern.
If I remove the second semicolon:
object main {
def main(args: Array[String]): Unit = {
for (
i <- 1 to 10
if i % 2 == 0;
j <- 2 to 8
if j % 2 == 1
) {
println(s"i: ${i}, j: ${j}")
val t = i + j
println(s"t: ${t}")
}
}
}
It works fine.
How to explain this behavior?
for comprehension can be defined using () or {}. Separator in case of () is ; and in case of {} is new line.
You are mixing both of them.
Try below (uses {} and new line separator):
object main {
def main(args: Array[String]): Unit = {
for {
i <- 1 to 10
if i % 2 == 0
j <- 2 to 8
if j % 2 == 1
} {
println(s"i: ${i}, j: ${j}")
val t = i + j
println(s"t: ${t}")
}
}
}
Below one uses () and ; separator:
object main {
def main(args: Array[String]): Unit = {
for (i <- 1 to 10 if i % 2 == 0; j <- 2 to 8 if j % 2 == 1) {
println(s"i: ${i}, j: ${j}")
val t = i + j
println(s"t: ${t}")
}
}
}

How to Make Prime Generator Code More Efficient

As a beginner in Scala, I got a problem in SPOJ:
Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!
Input
The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output
For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.
Example
Input:
2
1 10
3 5
Output:
2
3
5
7
3
5
`
Warning: large Input/Output data, be careful with certain languages (though most should be OK if the algorithm is well designed)
Run environment and requirement:
Added by: Adam Dzedzej
Date: 2004-05-01
Time limit: 6s
Source limit: 50000B
Memory limit: 1536MB
Cluster: Cube (Intel Pentium G860 3GHz)
Languages: All except: NODEJS PERL 6 SCM chicken
My code is here:
import math.sqrt
object Pro_2 {
def main(args: Array[String]) {
// judge whether a Long is a prime or not
def isPrime(num: Long): Boolean = {
num match {
case num if (num < 2) => false
case _ => {
2 to (sqrt(num) toInt) forall (num % _ != 0)
}
}
}
// if a Long is a prime print it in console
def printIfIsPrime(num: Long) = {
if (isPrime(num))
println(num)
}
// get range
def getInput(times: Int) = {
for (input <- 0 until times) yield {
val range = readLine().split(" ")
(range(0) toLong, range(1) toLong)
}
}
val ranges = getInput(readInt())
for (time <- 0 until ranges.length) {
(ranges(time)._1 to ranges(time)._2).foreach(printIfIsPrime(_))
if (time != ranges.length - 1)
println()
}
}
}
When I run my code in SPOJ, I got a result: time limit exceeded
I need make my code more efficient, could you please help me?
Any help would be greatly appreciated.
isPrime could be written in a lower level style. Also you can increase the speed of the println method.
def main(args: Array[String]) {
val out = new java.io.PrintWriter(System.out, false)
def isPrime(n: Long): Boolean = {
if(n <= 3) return n > 1
else if(n%2 == 0 || n%3 == 0) return false
else {
var i = 5
while(i*i <= n) {
if(n%i == 0 || n%(i+2) == 0) return false
i += 6
}
return true
}
}
def printIfIsPrime(num: Long) = {
if (isPrime(num)) {
out.println(num)
}
}
...
val ranges = getInput(readInt())
for (time <- 0 until ranges.length) {
(ranges(time)._1 to ranges(time)._2).foreach(printIfIsPrime(_))
if (time != ranges.length - 1)
out.println()
}
out.flush()
}

Swapping array values with for and yield scala

I am trying to swap every pair of values in my array using for and yield and so far I am very unsuccessful. What I have tried is as follows:
val a = Array(1,2,3,4,5) //What I want is Array(2,1,4,3,5)
for(i<-0 until (a.length-1,2),r<- Array(i+1,i)) yield r
The above given snippet returns the vector 2,1,4,3(and the 5 is omitted)
Can somebody point out what I am doing wrong here and how to get the correct reversal using for and yields?
Thanks
a.grouped(2).flatMap(_.reverse).toArray
or if you need for/yield (much less concise in this case, and in fact expands to the same code):
(for {b <- a.grouped(2); c <- b.reverse} yield c).toArray
It would be easier if you didin't use for/yield:
a.grouped(2)
.flatMap{
case Array(x,y) => Array(y,x)
case Array(x) => Array(x)
}.toArray // Array(2, 1, 4, 3, 5)
I don't know if the OP is reading Scala for the Impatient, but this was exercise 3.3 .
I like the map solution, but we're not on that chapter yet, so this is my ugly implementation using the required for/yield. You can probably move some yield logic into a guard/definition.
for( i <- 0 until(a.length,2); j <- (i+1).to(i,-1) if(j<a.length) ) yield a(j)
I'm a Java guy, so I've no confirmation of this assertion, but I'm curious what the overhead of the maps/grouping and iterators are. I suspect it all compiles down to the same Java byte code.
Another simple, for-yield solution:
def swapAdjacent(array: ArrayBuffer[Int]) = {
for (i <- 0 until array.length) yield (
if (i % 2 == 0)
if (i == array.length - 1) array(i) else array(i + 1)
else array(i - 1)
)
}
Here is my solution
def swapAdjacent(a: Array[Int]):Array[Int] =
(for(i <- 0 until a.length) yield
if (i%2==0 && (i+1)==a.length) a(i) //last element for odd length
else if (i%2==0) a(i+1)
else a(i-1)
).toArray
https://github.com/BasileDuPlessis/scala-for-the-impatient/blob/master/src/main/scala/com/basile/scala/ch03/Ex03.scala
If you are doing exercises 3.2 and 3.3 in Scala for the Impatient here are both my answers. They are the same with the logic moved around.
/** Excercise 3.2 */
for (i <- 0 until a.length if i % 2 == 1) {val t = a(i); a(i) = a(i-1); a(i-1) = t }
/** Excercise 3.3 */
for (i <- 0 until a.length) yield { if (i % 2 == 1) a(i-1) else if (i+1 <= a.length-1) a(i+1) else a(i) }
for (i <- 0 until arr.length-1 by 2) { val tmp = arr(i); arr(i) = arr(i+1); arr(i+1) = tmp }
I have started to learn Scala recently and all solutions from the book Scala for the Impatient (1st edition) are available at my github:
Chapter 2
https://gist.github.com/carloscaldas/51c01ccad9d86da8d96f1f40f7fecba7
Chapter 3
https://gist.github.com/carloscaldas/3361321306faf82e76c967559b5cea33
I have my solution, but without yield. Maybe someone will found it usefull.
def swap(x: Array[Int]): Array[Int] = {
for (i <- 0 until x.length-1 by 2){
var left = x(i)
x(i) = x(i+1)
x(i+1) = left
}
x
}
Assuming array is not empty, here you go:
val swapResult = for (ind <- arr1.indices) yield {
if (ind % 2 != 0) arr1(ind - 1)
else if (arr1(ind) == arr1.last) arr1(ind)
else if (ind % 2 == 0) arr1(ind + 1)
}

How do I break out of a loop in Scala?

How do I break out a loop?
var largest=0
for(i<-999 to 1 by -1) {
for (j<-i to 1 by -1) {
val product=i*j
if (largest>product)
// I want to break out here
else
if(product.toString.equals(product.toString.reverse))
largest=largest max product
}
}
How do I turn nested for loops into tail recursion?
From Scala Talk at FOSDEM 2009 http://www.slideshare.net/Odersky/fosdem-2009-1013261
on the 22nd page:
Break and continue
Scala does not have them. Why?
They are a bit imperative; better use many smaller functions
Issue how to interact with closures.
They are not needed!
What is the explanation?
You have three (or so) options to break out of loops.
Suppose you want to sum numbers until the total is greater than 1000. You try
var sum = 0
for (i <- 0 to 1000) sum += i
except you want to stop when (sum > 1000).
What to do? There are several options.
(1a) Use some construct that includes a conditional that you test.
var sum = 0
(0 to 1000).iterator.takeWhile(_ => sum < 1000).foreach(i => sum+=i)
(warning--this depends on details of how the takeWhile test and the foreach are interleaved during evaluation, and probably shouldn't be used in practice!).
(1b) Use tail recursion instead of a for loop, taking advantage of how easy it is to write a new method in Scala:
var sum = 0
def addTo(i: Int, max: Int) {
sum += i; if (sum < max) addTo(i+1,max)
}
addTo(0,1000)
(1c) Fall back to using a while loop
var sum = 0
var i = 0
while (i <= 1000 && sum <= 1000) { sum += 1; i += 1 }
(2) Throw an exception.
object AllDone extends Exception { }
var sum = 0
try {
for (i <- 0 to 1000) { sum += i; if (sum>=1000) throw AllDone }
} catch {
case AllDone =>
}
(2a) In Scala 2.8+ this is already pre-packaged in scala.util.control.Breaks using syntax that looks a lot like your familiar old break from C/Java:
import scala.util.control.Breaks._
var sum = 0
breakable { for (i <- 0 to 1000) {
sum += i
if (sum >= 1000) break
} }
(3) Put the code into a method and use return.
var sum = 0
def findSum { for (i <- 0 to 1000) { sum += i; if (sum>=1000) return } }
findSum
This is intentionally made not-too-easy for at least three reasons I can think of. First, in large code blocks, it's easy to overlook "continue" and "break" statements, or to think you're breaking out of more or less than you really are, or to need to break two loops which you can't do easily anyway--so the standard usage, while handy, has its problems, and thus you should try to structure your code a different way. Second, Scala has all sorts of nestings that you probably don't even notice, so if you could break out of things, you'd probably be surprised by where the code flow ended up (especially with closures). Third, most of Scala's "loops" aren't actually normal loops--they're method calls that have their own loop, or they are recursion which may or may not actually be a loop--and although they act looplike, it's hard to come up with a consistent way to know what "break" and the like should do. So, to be consistent, the wiser thing to do is not to have a "break" at all.
Note: There are functional equivalents of all of these where you return the value of sum rather than mutate it in place. These are more idiomatic Scala. However, the logic remains the same. (return becomes return x, etc.).
This has changed in Scala 2.8 which has a mechanism for using breaks. You can now do the following:
import scala.util.control.Breaks._
var largest = 0
// pass a function to the breakable method
breakable {
for (i<-999 to 1 by -1; j <- i to 1 by -1) {
val product = i * j
if (largest > product) {
break // BREAK!!
}
else if (product.toString.equals(product.toString.reverse)) {
largest = largest max product
}
}
}
It is never a good idea to break out of a for-loop. If you are using a for-loop it means that you know how many times you want to iterate. Use a while-loop with 2 conditions.
for example
var done = false
while (i <= length && !done) {
if (sum > 1000) {
done = true
}
}
To add Rex Kerr answer another way:
(1c) You can also use a guard in your loop:
var sum = 0
for (i <- 0 to 1000 ; if sum<1000) sum += i
Simply We can do in scala is
scala> import util.control.Breaks._
scala> object TestBreak {
def main(args : Array[String]) {
breakable {
for (i <- 1 to 10) {
println(i)
if (i == 5)
break;
} } } }
output :
scala> TestBreak.main(Array())
1
2
3
4
5
Since there is no break in Scala yet, you could try to solve this problem with using a return-statement. Therefore you need to put your inner loop into a function, otherwise the return would skip the whole loop.
Scala 2.8 however includes a way to break
http://www.scala-lang.org/api/rc/scala/util/control/Breaks.html
An approach that generates the values over a range as we iterate, up to a breaking condition, instead of generating first a whole range and then iterating over it, using Iterator, (inspired in #RexKerr use of Stream)
var sum = 0
for ( i <- Iterator.from(1).takeWhile( _ => sum < 1000) ) sum += i
// import following package
import scala.util.control._
// create a Breaks object as follows
val loop = new Breaks;
// Keep the loop inside breakable as follows
loop.breakable{
// Loop will go here
for(...){
....
// Break will go here
loop.break;
}
}
use Break module
http://www.tutorialspoint.com/scala/scala_break_statement.htm
Just use a while loop:
var (i, sum) = (0, 0)
while (sum < 1000) {
sum += i
i += 1
}
Here is a tail recursive version. Compared to the for-comprehensions it is a bit cryptic, admittedly, but I'd say its functional :)
def run(start:Int) = {
#tailrec
def tr(i:Int, largest:Int):Int = tr1(i, i, largest) match {
case x if i > 1 => tr(i-1, x)
case _ => largest
}
#tailrec
def tr1(i:Int,j:Int, largest:Int):Int = i*j match {
case x if x < largest || j < 2 => largest
case x if x.toString.equals(x.toString.reverse) => tr1(i, j-1, x)
case _ => tr1(i, j-1, largest)
}
tr(start, 0)
}
As you can see, the tr function is the counterpart of the outer for-comprehensions, and tr1 of the inner one. You're welcome if you know a way to optimize my version.
Close to your solution would be this:
var largest = 0
for (i <- 999 to 1 by -1;
j <- i to 1 by -1;
product = i * j;
if (largest <= product && product.toString.reverse.equals (product.toString.reverse.reverse)))
largest = product
println (largest)
The j-iteration is made without a new scope, and the product-generation as well as the condition are done in the for-statement (not a good expression - I don't find a better one). The condition is reversed which is pretty fast for that problem size - maybe you gain something with a break for larger loops.
String.reverse implicitly converts to RichString, which is why I do 2 extra reverses. :) A more mathematical approach might be more elegant.
I am new to Scala, but how about this to avoid throwing exceptions and repeating methods:
object awhile {
def apply(condition: () => Boolean, action: () => breakwhen): Unit = {
while (condition()) {
action() match {
case breakwhen(true) => return ;
case _ => { };
}
}
}
case class breakwhen(break:Boolean);
use it like this:
var i = 0
awhile(() => i < 20, () => {
i = i + 1
breakwhen(i == 5)
});
println(i)
if you don’t want to break:
awhile(() => i < 20, () => {
i = i + 1
breakwhen(false)
});
The third-party breakable package is one possible alternative
https://github.com/erikerlandson/breakable
Example code:
scala> import com.manyangled.breakable._
import com.manyangled.breakable._
scala> val bkb2 = for {
| (x, xLab) <- Stream.from(0).breakable // create breakable sequence with a method
| (y, yLab) <- breakable(Stream.from(0)) // create with a function
| if (x % 2 == 1) continue(xLab) // continue to next in outer "x" loop
| if (y % 2 == 0) continue(yLab) // continue to next in inner "y" loop
| if (x > 10) break(xLab) // break the outer "x" loop
| if (y > x) break(yLab) // break the inner "y" loop
| } yield (x, y)
bkb2: com.manyangled.breakable.Breakable[(Int, Int)] = com.manyangled.breakable.Breakable#34dc53d2
scala> bkb2.toVector
res0: Vector[(Int, Int)] = Vector((2,1), (4,1), (4,3), (6,1), (6,3), (6,5), (8,1), (8,3), (8,5), (8,7), (10,1), (10,3), (10,5), (10,7), (10,9))
import scala.util.control._
object demo_brk_963
{
def main(args: Array[String])
{
var a = 0;
var b = 0;
val numList1 = List(1,2,3,4,5,6,7,8,9,10);
val numList2 = List(11,12,13);
val outer = new Breaks; //object for break
val inner = new Breaks; //object for break
outer.breakable // Outer Block
{
for( a <- numList1)
{
println( "Value of a: " + a);
inner.breakable // Inner Block
{
for( b <- numList2)
{
println( "Value of b: " + b);
if( b == 12 )
{
println( "break-INNER;");
inner.break;
}
}
} // inner breakable
if( a == 6 )
{
println( "break-OUTER;");
outer.break;
}
}
} // outer breakable.
}
}
Basic method to break the loop, using Breaks class.
By declaring the loop as breakable.
Ironically the Scala break in scala.util.control.Breaks is an exception:
def break(): Nothing = { throw breakException }
The best advice is: DO NOT use break, continue and goto! IMO they are the same, bad practice and an evil source of all kind of problems (and hot discussions) and finally "considered be harmful". Code block structured, also in this example breaks are superfluous.
Our Edsger W. Dijkstra† wrote:
The quality of programmers is a decreasing function of the density of go to statements in the programs they produce.
I got a situation like the code below
for(id<-0 to 99) {
try {
var symbol = ctx.read("$.stocks[" + id + "].symbol").toString
var name = ctx.read("$.stocks[" + id + "].name").toString
stocklist(symbol) = name
}catch {
case ex: com.jayway.jsonpath.PathNotFoundException=>{break}
}
}
I am using a java lib and the mechanism is that ctx.read throw a Exception when it can find nothing.
I was trapped in the situation that :I have to break the loop when a Exception was thrown, but scala.util.control.Breaks.break using Exception to break the loop ,and it was in the catch block thus it was caught.
I got ugly way to solve this: do the loop for the first time and get the count of the real length.
and use it for the second loop.
take out break from Scala is not that good,when you are using some java libs.
Clever use of find method for collection will do the trick for you.
var largest = 0
lazy val ij =
for (i <- 999 to 1 by -1; j <- i to 1 by -1) yield (i, j)
val largest_ij = ij.find { case(i,j) =>
val product = i * j
if (product.toString == product.toString.reverse)
largest = largest max product
largest > product
}
println(largest_ij.get)
println(largest)
Below is code to break a loop in a simple way
import scala.util.control.Breaks.break
object RecurringCharacter {
def main(args: Array[String]) {
val str = "nileshshinde";
for (i <- 0 to str.length() - 1) {
for (j <- i + 1 to str.length() - 1) {
if (str(i) == str(j)) {
println("First Repeted Character " + str(i))
break() //break method will exit the loop with an Exception "Exception in thread "main" scala.util.control.BreakControl"
}
}
}
}
}
I don't know how much Scala style has changed in the past 9 years, but I found it interesting that most of the existing answers use vars, or hard to read recursion. The key to exiting early is to use a lazy collection to generate your possible candidates, then check for the condition separately. To generate the products:
val products = for {
i <- (999 to 1 by -1).view
j <- (i to 1 by -1).view
} yield (i*j)
Then to find the first palindrome from that view without generating every combination:
val palindromes = products filter {p => p.toString == p.toString.reverse}
palindromes.head
To find the largest palindrome (although the laziness doesn't buy you much because you have to check the entire list anyway):
palindromes.max
Your original code is actually checking for the first palindrome that is larger than a subsequent product, which is the same as checking for the first palindrome except in a weird boundary condition which I don't think you intended. The products are not strictly monotonically decreasing. For example, 998*998 is greater than 999*997, but appears much later in the loops.
Anyway, the advantage of the separated lazy generation and condition check is you write it pretty much like it is using the entire list, but it only generates as much as you need. You sort of get the best of both worlds.

Scala downwards or decreasing for loop?

In Scala, you often use an iterator to do a for loop in an increasing order like:
for(i <- 1 to 10){ code }
How would you do it so it goes from 10 to 1? I guess 10 to 1 gives an empty iterator (like usual range mathematics)?
I made a Scala script which solves it by calling reverse on the iterator, but it's not nice in my opinion, is the following the way to go?
def nBeers(n:Int) = n match {
case 0 => ("No more bottles of beer on the wall, no more bottles of beer." +
"\nGo to the store and buy some more, " +
"99 bottles of beer on the wall.\n")
case _ => (n + " bottles of beer on the wall, " + n +
" bottles of beer.\n" +
"Take one down and pass it around, " +
(if((n-1)==0)
"no more"
else
(n-1)) +
" bottles of beer on the wall.\n")
}
for(b <- (0 to 99).reverse)
println(nBeers(b))
scala> 10 to 1 by -1
res1: scala.collection.immutable.Range = Range(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
The answer from #Randall is good as gold, but for sake of completion I wanted to add a couple of variations:
scala> for (i <- (1 to 10).reverse) {code} //Will count in reverse.
scala> for (i <- 10 to(1,-1)) {code} //Same as with "by", just uglier.
Scala provides many ways to work on downwards in loop.
1st Solution: with "to" and "by"
//It will print 10 to 0. Here by -1 means it will decremented by -1.
for(i <- 10 to 0 by -1){
println(i)
}
2nd Solution: With "to" and "reverse"
for(i <- (0 to 10).reverse){
println(i)
}
3rd Solution: with "to" only
//Here (0,-1) means the loop will execute till value 0 and decremented by -1.
for(i <- 10 to (0,-1)){
println(i)
}
Having programmed in Pascal, I find this definition nice to use:
implicit class RichInt(val value: Int) extends AnyVal {
def downto (n: Int) = value to n by -1
def downtil (n: Int) = value until n by -1
}
Used this way:
for (i <- 10 downto 0) println(i)
You can use Range class:
val r1 = new Range(10, 0, -1)
for {
i <- r1
} println(i)
You can use :
for (i <- 0 to 10 reverse) println(i)
for (i <- 10 to (0,-1))
The loop will execute till the value == 0, decremented each time by -1.