Support of `do..while` Loop In scala - scala

Hello everyone I am new to scala and after seeing the do..while syntax which is the following:
do{
<action>
}while(condition)
I have been asked to perform this exercise which consists in predicting the output of a program containing the do..while loop.
var set = Set(1)
do {
set = set + (set.max + 1)
} while (set.sum < 32)
println(set.size)
After execution I get the following error:
end of statement expected but 'do' found
do {
I know that it is possible to convert this loop to while (which is even ideal), however I would like to know if the do..while loop still works in scala if yes, is it a syntax error (Because I searched on the net but I found the same syntax and no mention of this error)? if no, is there a version from which the loop is no longer supported?

You can still use do-while in Scala 2.13.10
https://scastie.scala-lang.org/DmytroMitin/JcGnZS3DRle3jXIUiwkb0A
In Scala 3 you can write do-while in while-do manner using Scala being expression-oriented (i.e. the last expression is what is returned from a block)
while ({
set = set + (set.max + 1)
set.sum < 32
}) {}
https://scastie.scala-lang.org/DmytroMitin/JcGnZS3DRle3jXIUiwkb0A/2
https://docs.scala-lang.org/scala3/reference/dropped-features/do-while.html

Related

scala nested for/yield generator to extract substring

I am new to scala. Pls be gentle. My problem for the moment is the syntax error.
(But my ultimate goal is to print each group of 3 characters from every string in the list...now i am merely printing the first 3 characters of every string)
def do_stuff():Unit = {
val s = List[String]("abc", "fds", "654444654")
for {
i <- s.indices
r <- 0 to s(i).length by 3
println(s(i).substring(0,3))
} yield {s(i)}
}
do_stuff()
i am getting this error. it is syntax related, but i dont undersatnd..
Error:(12, 18) ')' expected but '.' found.
println(s(i).substring(0,3))
That code doesn't compile because in a for-comprehension, you can't just put a print statement, you always need an assignment, in this case, a dummy one can solve your porblem.
_ = println(s(i).substring(0,3))
EDIT
If you want the combination of 3 elements in every String you can use combinations method from collections.
List("abc", "fds", "654444654").flatMap(_.combinations(3).toList)

Are Scala closures as flexible as C++ lambdas?

I know the question seems a bit heretical. Indeed, having much appreciated lambdas in C++11, I was quite thrilled to learn a language which was built to support them from the beginning rather than as a contrived addition.
However, I cannot figure out how to do with Scala all I can do with C++11 lambdas.
Suppose I want to make a function which adds to a number passed as a parameter some value contained in a variable a. In C++, I can do both
int a = 5;
auto lambdaVal = [ a](int par) { return par + a; };
auto lambdaRef = [&a](int par) { return par + a; };
Now, if I change a, the second version will change its behavior; but the first will keep adding 5.
In Scala, if I do this
var a = 5
val lambdaOnly = (par:Int) => par + a
I essentially get the lambdaRef model: changing a will immediately change what the function does.
(which seems somewhat specious to me given that this time a isn't even mentioned in the declaration of the lambda, only in its code. But let it be)
Am I missing the way to obtain lambdaVal? Or do I have to first copy a to a val to be free to modify it afterwards without side effects?
The a in the function definition refers the variable a. If you want to use the current value of a when the lambda has been created, you have to copy the value like this:
val lambdaConst = {
val aNow = a
(par:Int) => par + aNow
}

Powershell If Statement Condition With Math Calculation

I'm currently having issues with Powershell. This is the line that errors:
while($minutes -le ($total_bots/$increment)) {
All of the above variables are numbers. I'm getting an error saying that it can't convert 60/5 - ($total_bots/$increment) - to a int32. I want the math operation completed, and then the condition evaluated. What am I missing?
Variables are declared like so:
[int]$minutes = 1
[int]$increment = 5
[int]$total_bots = 20
I didn't have the int there initially, but it still errors with it.
Was erroring below this after I changed them to [int]. Works now. Thanks

EPL syntax wrong

I am very new to EPL queries.
Wrote this and it is throwing syntax error.
#Name('ExpressionTotalQuantitySoFar')
#Description('Gets the total quantity of a symbol so far')
create expression totalQuantitySoFar{ (TAX) =>
(Select sum(T.quantity) from TaxlotWindow as T where T.symbol = TAX.symbol and T.taxlotId < TAX.taxlotId)
};
create variable double totQty = 5.0 ;
#Name('ExpressionLongDebitBalanceTaxlotNoBox')
#Description('Check is if a trade side is invalid, returns rue for invalid statements')
create expression longDebitBalanceTaxlotNoBox{ (SECUR,TAX,ORD,AUE,FX) =>
totQty = totalQuantitySoFar(TAX)
case when (totQty > 0)
then cashImpactBase(SECUR,TAX,ORD,AUE,FX)*(-1)
else
0.0
end
};
It gives syntax error near case.
Any help?
Always include the syntax error text when posting. Else how is one supposed to be able to help.
My tip would be to simplify until the syntax is fine. Then add back stuff.
Most likely this strange declaration "totQty=.." is the cause as its wrong. EPL expressions are not a programming language and don't allow variable declarations like in Java or Scala. Perhaps just use a Java static method to compute instead of you need a programming language.

Why does Scala's semicolon inference fail here?

On compiling the following code with Scala 2.7.3,
package spoj
object Prime1 {
def main(args: Array[String]) {
def isPrime(n: Int) = (n != 1) && (2 to n/2 forall (n % _ != 0))
val read = new java.util.Scanner(System.in)
var nTests = read nextInt // [*]
while(nTests > 0) {
val (start, end) = (read nextInt, read nextInt)
start to end filter(isPrime(_)) foreach println
println
nTests -= 1
}
}
}
I get the following compile time error :
PRIME1.scala:8: error: illegal start of simple expression
while(nTests > 0) {
^
PRIME1.scala:14: error: block must end in result expression, not in definition
}
^
two errors found
When I add a semicolon at the end of the line commented as [*], the program compiles fine. Can anyone please explain why does Scala's semicolon inference fail to work on that particular line?
Is it because scala is assuming that you are using the syntax a foo b (equivalent to a.foo(b)) in your call to readInt. That is, it assumes that the while loop is the argument to readInt (recall that every expression has a type) and hence the last statement is a declaration:
var ntests = read nextInt x
wherex is your while block.
I must say that, as a point of preference, I've now returned to using the usual a.foo(b) syntax over a foo b unless specifically working with a DSL which was designed with that use in mind (like actors' a ! b). It makes things much clearer in general and you don't get bitten by weird stuff like this!
Additional comment to the answer by oxbow_lakes...
var ntests = read nextInt()
Should fix things for you as an alternative to the semicolon
To add a little more about the semicolon inference, Scala actually does this in two stages. First it infers a special token called nl by the language spec. The parser allows nl to be used as a statement separator, as well as semicolons. However, nl is also permitted in a few other places by the grammar. In particular, a single nl is allowed after infix operators when the first token on the next line can start an expression -- and while can start an expression, which is why it interprets it that way. Unfortunately, although while can start a expression, a while statement cannot be used in an infix expression, hence the error. Personally, it seems a rather quirky way for the parser to work, but there's quite plausibly a sane rationale behind it for all I know!
As yet another option to the others suggested, putting a blank newline between your [*] line and the while line will also fix the problem, because only a single nl is permitted after infix operators, so multiple nls forces a different interpretation by the parser.