I was wondering if there is any possibility to implement a logical implication in scala.
For example:
a implies b
translating into:
!a || b
where a and b are some expressions that evaluate to Boolean.
I initially started with following, but that is a wrong approach
implicit def extendedBoolean(a : Boolean) = new {
def implies(b : Boolean) = {
!a || b
}
}
since it will evaluate both a and b regardless the value of a. The correct solution would only evaluate b when a is true.
You want to use a call-by-name parameter, I believe the following should suffice:
Explanation:
You must pass some value in for
bbut you do not want that expression evaluated; Scala can automatically convert the expression into a function that takes no arguments and evaluates to the expression. Yourimpliesoperator then evaluates that nullary (zero-argument) function if need be.The compiler knows that it can do this conversion because of the type signature you have provided,
=> Boolean. This post explains in better detail, but its title alone is a very good nutshell explanation of what is going on: “Automatic Type-Dependent Closure Construction”.This feature of Scala enables one to write control constructs, perhaps as easily as one might write them using macros in other languages. Observe how easily they reimplement a while loop using two call-by-name parameters: one for the conditional and one for the body.