Select all correct implementations of the or(x,y) function that for all argument expressions x and y , it evaluates same as x || y boolean expression.
Explanation
Get an explanation when it's available:
Theory
  • Boolean expressions b can be composed of
    true false // Constants
    !b // Negation
    b && b // Conjunction
    b || b // Disjunction
    
    and of the usual comparison operations:
    e <= e, e >= e, e < e, e > e, e == e, e != e
    Here are reduction rules for Boolean expressions (e is an arbitrary expression):
    !true --> false
    !false --> true
    true && e --> e
    false && e --> false
    true || e --> true
    false || e --> e
    
    Note that && and || do not always need their right operand to be evaluated.
    We say, these expressions use “short-circuit evaluation”.
  • To express choosing between two alternatives, Scala has a conditional expression if-else. It looks like a if-else in Java, but is used for expressions, not statements.
    Example:
    def abs(x: Int) = if (x >= 0) x else -x
    
    x >= 0 is a predicate, of type Boolean.
    Here are reduction rules for conditional expressions (e1 and e2 are arbitrary expressions, b is boolean expression)
    if (b) e1 else e2:
    if (true) e1 else e2   --> e1
    if (false) e1 else e2  --> e2
    
  • Function parameters can be passed by value or be passed by name.
    The same distinction applies to definitions.
    The def form is “by-name”, its right hand side is evaluated on each use.
    There is also a val form, which is “by-value”.
    Example:
    val x = 2
    val y = square(x)
    
    The right-hand side of a val definition is evaluated at the point of the definition itself.
    Afterwards, the name refers to the value. For instance, y above refers to 4, not square(2).
  • The difference between val and def becomes apparent when the right hand side does not terminate.
    Given
    def loop: Boolean = loop
    
    A definition
    def x = loop
    
    is OK, but a definition
    val x = loop
    
    will lead to an infinite loop.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Scala quizzes
Cosmo
Sign Up Now
or Subscribe for future quizzes