sicp.io
1.1.5 · Conditional expressions and predicates

A predicate chooses which work becomes real.

Use if, cond, and composed predicates to select one branch, then observe how and and or stop before expressions whose values are no longer needed.

Guiding question

How can a program make a decision without evaluating the work belonging to every possible branch?

  • Read a predicate as an expression that controls a later evaluation path
  • Follow the first matching cond clause and its else fallback
  • Use if to protect an operation whose precondition is not satisfied
  • Remember that only #f is false in Scheme-compatible Lispex code
  • Observe short-circuit evaluation through explicit side effects

A conditional does not compute every answer and choose afterward. It evaluates a test, selects one path, and leaves the other path unevaluated. classify tries cond predicates from top to bottom. safe-ratio uses if to avoid division when the denominator is zero. The quoted symbol non-false selects the true branch because only #f counts as false.

and and or are control forms rather than ordinary procedures. and stops at the first false value; or stops at the first value that is not #f. The second program records only the operands that are actually reached, making the skipped expressions visible by their absence. This finite run demonstrates the selected path, not every possible optimizer or implementation strategy.

SICP code468 of 1,048,576 UTF-8 bytes
Examples
Result
Output
Value
Diagnostic
Execution trace0 / 0 events
    Programs run in the browser with their result and execution trace.
    Expected result

    The first program returns (negative zero small-positive large-positive undefined 5 truthy). The second returns (#f selected (or-ran and-ran)); the two labels ending in skipped never enter visits.

    Trace focus

    Find each predicate before its selected branch. Confirm that the division expression is absent when the denominator is zero. In the short-circuit program, locate the first #f in and and the first non-#f value in or, then verify that no application event exists for either skipped record! call.

    Try it yourself

    Change the program and compare the result.

    Add a between? predicate and use it inside cond to distinguish negative, zero, one-digit positive, two-digit positive, and larger values. Then add one record! call after a guaranteed false and operand and predict whether it runs.

    Show hint

    A helper predicate can combine lower and upper comparisons with and. Anything placed after a false and operand is unreachable in that evaluation.

    Complete this lesson

    0 of 18 lessons complete in this chapter0%