Implementing the implication boolean operator in scala

I was wondering if it is possible to implement logical implication in scala. For instance:

a implies b

translation to:

!a || b

where aand bare some expressions that are evaluated as Boolean.

At first I started with the following, but this is the wrong approach

  implicit def extendedBoolean(a : Boolean) = new {
    def implies(b : Boolean) = {
      !a || b
    }
  }

as he will evaluate both a, and bregardless of value a. The right decision will be judged only bwhen atrue.

+3
source share
2 answers

You want to use the parameter to call by name, I believe the following should be sufficient:

implicit def extendedBoolean(a : Boolean) = new {
    def implies(b : => Boolean) = {
      !a || b
    }
  }

Explanation:

b, , ; Scala , . implies ( ) , .

, - , , => Boolean. , , : " " .

Scala , , , . , while, : .

object TargetTest2 extends Application {
  //type signature not too terribly mysterious
  def whileLoop(cond: => Boolean)(body: => Unit): Unit =
    if (cond) {
      body
      whileLoop(cond)(body)
    }

  //about as easy to use as a plain-old while() loop
  var i = 10
  whileLoop (i > 0) {
    println(i)
    i -= 1
  }
}
+5

b , . , , .

, => Boolean, , Boolean .

implicit def extendedBoolean(a: Boolean) = new {
  def implies(b: => Boolean) = {
    !a || b
  }
}

, :

scala> true implies { println("evaluated"); true }
evaluated
res0: Boolean = true

scala> false implies { println("evaluated"); true }
res1: Boolean = true

, a true, b ( "" ). a false, ( ).

+4

All Articles