Scalastyle Boolean expression can be simplified - scala

Scalastyle (intellij 2016.1 defaults) says this boolean expression can be simplified
val t = Option(true)
val f = Option(false)
if(t.contains(true) && f.contains(false)) {
println("booop")
}
I can get rid of this by changing the if to:
if(t.contains(true).&&(f.contains(false)))
Or by changing && to &
But not really seeing how this is simplifying it, could anyone explain what's going on?
Update
It doesn't appear to be related to if the vals are known at compile time, or them being locally defined. The following code also get's the warning that the expression can be simplfied:
object TestFoo {
def bar(t: Option[Boolean]) = {
val f = Option(scala.util.Random.nextBoolean)
if (t.contains(true) && f.contains(false)) println("booop")
}
def main(args: Array[String]) = bar(t = Option(scala.util.Random.nextBoolean))
}
I just don't get how I'm supposed to make that any simpler, is there some strange Option[Boolean] comparing I'm missing out on?

It seems to suggest you being consistent with the method call usage. Either everything in infix form:
(t contains true) && (f contains false)
Or everything in regular method call form:
t.contains(true).&&(f.contains(false))

With your values, t.contains(true).&&(f.contains(false)) always returns true. So you could simplify it by simply writing true, i.e by just executing the print without an if condition.

Related

Have && short circuit with :| in expressions in ScalaCheck

I am attempting to create a property-based test in a Scala Test FlatSpec that uses the ScalaCheck :| operator to give failure messages for different parts of the ending boolean expression.
However, I am running into an issue where the && operator does not short circuit. In this case the earlier part of the expression checks to see if the next part of the expression can be run, otherwise that later section would throw an exception.
Here is an example of what the issue looks like. If decoded is None, then the expression should short circuit on the && so that decoded.get is not run, as it would throw an exception.
val value: Array[Int] = Array.fill(2)(0)
val encoded = encode(value)
val decoded: Option[Array[Int]] = decode(value)
decoded.isDefined :| "decoded None" &&
value.sameElements(decoded.get)
When I write the boolean without using the :| operator to give a failure message, the test fails on the decoded.isDefined without throwing an exception.
val value: Array[Int] = Array.fill(2)(0)
val encoded = encode(value)
val decoded: Option[Array[Int]] = decode(value)
decoded.isDefined &&
value.sameElements(decoded.get)
However, when I include a failure message with :|, it fails with a NoSuchElementException on the value.sameElements(decoded.get) line and does not display the failure message for decoded.isDefined even though it would evaluate to false.
The imports and test class declaration I am using are the following:
import org.scalacheck.Prop._
import org.scalatest.prop.Checkers
import org.scalatest.{FlatSpec, Matchers}
class ByteRWTests extends FlatSpec with Matchers with Checkers {
I am writing property checks in the following manner:
it should "be equal" in {
check(
forAll { (int: Int) =>
int == int
}
)
}
Is there any way to get the short circuiting for && to work with expressions using :|, or is there a workaround for this issue?
Why you see the difference
The issue is that while the && for booleans is short-circuiting, the && method on Prop isn't, and whether or not you use a label determines where the implicit conversion from boolean to Prop happens. For example:
import org.scalacheck.Prop, Prop._
val value: Array[Int] = Array.fill(2)(0)
val decoded: Option[Array[Int]] = None
val p1: Prop = decoded.isDefined && value.sameElements(decoded.get)
val p2: Prop = decoded.isDefined :| "decoded None" && value.sameElements(decoded.get)
Here the p1 definition desugars to this:
Prop.propBoolean(decoded.isDefined && value.sameElements(decoded.get))
While p2 gives you this:
(Prop.propBoolean(decoded.isDefined) :| "decoded None").&&(
Prop.propBoolean(value.sameElements(decoded.get))
)
(For what it's worth this is another example of why I don't like fancy implicit-conversion-based DSLs.)
Workaround
Unfortunately it's just not possible to get the && method on Prop to do what you want here, but you can define your own version of conjunction that does:
def propAnd(p1: => Prop, p2: => Prop) = p1.flatMap { r =>
if (r.success) Prop.secure(p2) else Prop(_ => r)
}
And then:
scala> propAnd(decoded.isDefined :| "decoded None" , value.sameElements(decoded.get))
res1: org.scalacheck.Prop = Prop
scala> .check
! Falsified after 0 passed tests.
> Labels of failing property:
decoded None
This method actually exists in ScalaCheck, but it's not part of the public API. A comment on the implementation does note that it "(Should maybe be in Prop module)", so if you find you're doing this kind of thing a lot, you might try opening a pull request to move the method from Commands to Prop and make it public.
In the specific case you've given here, though, I'd probably suggest using something like exists on the Option instead of checking whether it's defined and then using get.

Scala: Expression of type Unit doesn't conform to type List[List[Boolean]]

I'm trying to produce a function that returns a List that contains Lists of Booleans in Scala. So far, the function looks like this:
def listListBool(n: Int): List[List[Boolean]] = {
val empty: List[List[Boolean]] = null
if (n == 0) {empty}
else if (n ==1) {val bools = List(List(true, false))
}
The 'else if' part of the statement flags up with the error: "Expression of type Unit doesn't conform to type List[List[Boolean]]" even though I have specified that the program needs to return a List of Lists of Booleans. I have also tried the following syntax:
else if (n == 1) {val bools: List[List[Boolean]] = List(List(true, false)
But the same error is still produced. Am I missing something really obvious here? I feel like have been staring at this for hours and I still can't quite grasp what I'm getting wrong.
Please keep in mind that I'm quite new to Scala and I'm not entirely familiar with all the ins and outs of the language and its syntax.
EDIT: I replied to some comments on this stating that an 'else' was due to be added following fixing this problem. Looking through your comments, I tried adding one anyway and that was what fixed it. I still don't quite understand how that changes the return type from being 'Any' to the correct type but it works none the less.
There are several problems with this code. First you have a structure like
if ...
else if ...
This is wrong because it would yield Unit if neither the first nor the second condition were met. What you want is:
if ...
else if ... //optional
else ....
Secondly an assignment always yields Unit and val bools: List[List[Boolean]] = List(List(true, false) is an assignment. Just write List(List(true, false).
Third if you want to return the empty List you have to write:
List.empty
or better
Nil
I am surprised that you don't get an error for returning null.
val bools: List[List[Boolean]] = List(List(true, false) is an assignment, which is of type Unit you want List(List(true, false) without the assignment.
You can just write a simpler version instead of function doing the same.
def listListBool(n:Int) = if(n==0) Nil else List(List(true,false))
If you are using a Typesafe language, using null should completely be avoided.

Different outputs when stating return or not

I am new to scala and I am trying to learn it by writing a simple program to check if given a string each open paranthesis has its own closed parenthesis.
For example for the string "{{ssss{{}}}}}" the answer should be false.
The code I am using is the following:
package recfun
import common._
import scala.collection.mutable.Stack
object Main{
def main(args: Array[String]) {
println(balance("{{ssss{{}}}}}".toList))
}
def balance(chars: List[Char]): Boolean = {
val openParentheses : List[Char] = List('(','{','[')
val matchingParentheses = Map(
'}'-> '{',
']'->'[',
')'->'(');
val openParenthesesFound: Stack[Char] = Stack[Char]()
for (letter <- chars) {
if (openParentheses.contains(letter)) openParenthesesFound.push(letter)
else if (matchingParentheses.contains(letter)) {
if (openParenthesesFound.isEmpty || !openParenthesesFound.head.equals(matchingParentheses(letter))) return false
else
openParenthesesFound.pop
}
}
if (openParenthesesFound.nonEmpty) false else true
}
}
However, in the lines
if (openParenthesesFound.isEmpty || !openParenthesesFound.head.equals(matchingParentheses(letter))) return false
else
openParenthesesFound.pop
if I remove "return" as suggested by IntellijIdea the program fails and I get wrong answer: True.
Can anybody help me exaplaining me why it happens so? I am probably missing something.
Also, does anyone have a better solution for this kind of task?
Thank you very much for the help,
Giovanni
Intellij is wrong. Obviously, removing return statement changes the logic of your function.
Perhaps, what it means to tell you is that using return statements in scala is frowned upon in general. It is usually better to come up with a solution avoiding it. Same goes for mutable state actually ...
Something like this is one of the possibilities:
val parens = "{[(" zip "}])" toMap
object OpenP {
def unapply(c: Char) = parens.keys.find(_ == c)
}
object CloseP {
def unapply(c: Char) = parens.values.find(_ == c)
}
#tailrec
def balanced(s: List[Char], ps: List[Char] = Nil): Boolean = (ps, s) match {
case (stack, Nil) => stack.isEmpty
case (p :: stack, CloseP(c) :: tail) => c == parens(p) && balanced(tail, stack)
case (stack, OpenP(p) :: tail) => balanced(tail, p :: stack)
case (stack, c :: tail) => balanced(tail, stack)
}
Your code flow will substantially change depending on whether you use return in the middle of the for comprehension here.
If you use return, your balance method will exit with false the first time you end up in that code path, which seems to be what you want (return false when you encounter the first mismatched parenthesis, since you require that none exist).
If you don't use return, only the containing if-else block will evaluate to false (remember, everything in Scala is an expression) instead of exiting the whole method. Since you aren't assigning it or checking it, your check actually does pretty much nothing, you will loop the whole thing through, and the last statement returns true. So you need the return if you want to solve this problem in this manner.
However, Scala encourages functional programming style without mutable state (such as your Stack here). The simplest way to solve this problem that way would probably be recursion and using an accumulator to store the intermediate parenthesis stack - this way you don't need mutable state (vars or mutable collections). And you avoid using explicit returns (which is encouraged - also probably the reason why your IDE is notifying you about its use) since a method implicitly returns its last statement as its value and this is often simple to achieve with a recursive approach.

Run a script and get each lines result

I want to write a simple Scala script that runs some methods that are defined in another file.
Each line that runs this method requires information that won't be available until runtime. For simplicity sakes, I want to abstract that portion out.
Thus, I want to use Currying to get the result of each line in the script, then run the result again with the extra data.
object TestUtil {
// "control" is not known until runtime
def someTestMethod(x: Int, y: Int)(control: Boolean): Boolean = {
if (control) {
assert(x == y)
x == y
} else {
assert(x > y)
x > y
}
}
}
someTestMethod is defined in my primary codebase.
// testScript.sc
import <whateverpath>.TestUtil
TestUtil.someTestMethod(2,1)
TestUtil.someTestMethod(5,5)
Each line should return a function, that I need to rerun with a Boolean.
val control: Boolean = true
List[(Boolean) -> Boolean) testFuncs = runFile("testScript.sc")
testFuncs.foreach(_(control)) // Run all the functions that testScripts defined
(Sorry if this is a weird example, it's the simplest thing I can think of)
So far I have figured out how to parse the script, and get the Tree. However at that point I can't figure out how to execute each individual tree object and get the result. This is basically where I'm stuck!
val settings = new scala.tools.nsc.GenericRunnerSettings(println)
settings.usejavacp.value = true
settings.nc.value = true
val interpreter: IMain = new IMain(settings)
val treeResult: Option[List[Tree]] = interpreter.parse(
"""true
| 5+14""".stripMargin)
treeResult.get.foreach((tree: Tree) => println(tree))
the result of which is
true
5.$plus(14)
where 5 + 14 has not been evaluated, and I can't figure out how, or if this is even a worthwhile route to pursure
In the worst case you could toString your modified tree and then call interpreter.interpret:
val results = treeResult.get.map { tree: Tree => interpreter.interpret(tree.toString) }
It seems like it would be better to have the other file evaluate to something that can then be interpreted passing control (e.g. using the scalaz Reader Monad and for/yield syntax). But I assume you have good reasons for wanting to do this via an extra scala interpreter.

Is the arrow anti pattern a standard in Scala

The question first: Is the arrow anti pattern the way to do things in Scala?
I've been transitioning from Java to Scala for about 3 months now. I'm starting to see that the anti arrow pattern as a bit of a standard in Scala.
For example, in Java, I like to return from methods as soon as possible. We don't like a lot of inner nestings. If you have lots of them it's called the arrow anti pattern. You can read about it here: http://c2.com/cgi/wiki?ArrowAntiPattern
Java example:
boolean isValid(String input){
if (input.trim().length() <1) return false //return early
if (input.substring(0,3).equals("sth")) return false;
//do some more checks for validity then return true
return true
}
If I wrote this in Scala I'd have to use match-case statements which results in a lot of indenting. Keep in mind that this is just a dummy example where I try to convey only the nesting and indentation of Scala.
def isValid(input:String): Boolean = {
(input.trim.length < 1) match {
case true =>
input.substring(0,3) match {
case sthCase if(sthCase=="sth") =>
//do some more checks etc
//eventually arrive at the "true" branch
... case valid => true
case sthElse if (sthCase=="bla") => //some more code etc
case _ => false
}
case _ => false
}
}
I know this example could have been written the same way I wrote the Java one, but if instead of returning true or false I wanted to assign that value to a variable ie:val valid = (input.trim.length < 1) match ... then this is the only way to do it since you can't reassign to val. I could use var instead of val, but then I'd be using Java instead of Scala.
Question, re-iterated:
So the question is, is the arrow anti pattern the way to do things in Scala or am I missing something? Is there a better way to do in Scala what I just wrote (keeping in mind that I want that match statement result to be assigned to a val variable).
Note that you can always use decomposition in Scala as long as all parts of the code are single entry/single exit. This works because nested functions in Scala can access the local variables of the outer function. E.g.:
def isValid(input: String): Boolean = {
def testLength = input.trim.length >= 1
def testSomething = input.substring(0, 3) == "sth"
return testLength && testSomething
}
You can thus break down any arrow-like structure into its subcomponents as much as you desire.
Note also that using match for testing booleans or comparing something for equality is overkill.
Your java example can easily be translated to an if/else in scala without explicit return and without any additional levels of nesting.
def isValid(input: String) = {
if (input.trim().length() <1) false
else if (input.substring(0,3).equals("sth")) false
else true
}
if/else like everything in scala is an expression and has a return value, so you might as well use it for an assignment:
val isValid =
if (input.trim().length() <1) false
else if (input.substring(0,3).equals("sth")) false
else true
Or in this case you could also simply write
val isValid = (input.trim().length() >= 1) && (!input.substring(0,3).equals("sth"))
If there are too many returns in a function, functions are missing:
def isValid(s: String): Boolean = {
def isLengthValid = s.trim().length() > 0
def shouldNotContainsSomething = s.substring(0, 3) != "sth"
isLengthValid && shouldNotContainsSomething
}
Don't do the cargo cult just because some rule says so. The good thing in Scala is that you can do the best from both worlds -- e.g. sometimes algoritm written in a mutable style is much more clear than the immutable one.
By the way, there is also require method, which is used commonly for fail on validation (but it goes up with an exception).