← Math
Math

Boolean logic, sets, and predicates

Did removing the parentheses change who gets the discount?

Express a checkout policy precisely enough to review its affected accounts and items.

Outcome

Translate a policy into predicates, check how && and || group, quantify over the right set and keep an unknown fact unknown when it decides the answer.

Terminology (6)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Predicate
A statement about something that is true or false, such as “the account is flagged”.
Precedence
Which operator groups first. In all four languages here, && groups before ||, so a || b && c means a || (b && c).
De Morgan’s laws
!(a && b) equals !a || !b, and !(a || b) equals !a && !b. Negating a rule flips each operator.
Universal quantifier Also for all, ∀
A claim about every member of a set. Over an empty set it is true: no member breaks it.
Existential quantifier Also there exists, ∃
A claim that at least one member qualifies. Over an empty set it is false.
Three-valued logic
Logic with true, false and unknown. true || unknown is true and false && unknown is false; other unknown inputs stay unknown.

Why this matters

Access rules, discounts, feature flags and alerts are predicates combined with and, or and not. A missing pair of parentheses can grant something to exactly the accounts a veto was meant to stop, and a test suite that never builds that combination will pass. Quantifiers over empty sets and facts that are not known yet are the other two places where a plausible rule gives the wrong answer.

This lesson assumes true, false and the operators &&, || and !. How the abuse flag is decided upstream is outside it.

Predicates connect logic with sets

A predicate is a test that is true or false for an object, such as whether an account is new. Over a defined population, it identifies the set of objects that pass. AND selects the intersection of two sets, OR their union, and NOT the complement within that population.

Grouping determines which predicates are combined. A rule over a collection also needs a quantifier: every relevant item must qualify, or at least one must qualify. Choosing that relevant set is part of the rule. When a required fact is pending, keep its unknown state available until the known facts settle the decision.

01Define the facts

Write the policy as predicates

An online electronics store grants a welcome discount to new or referred customers, never to accounts flagged for promo abuse. A pull request tidied the rule to isNew || referred && !flagged, and its tests passed. Before it ships, find who the change affects.

Facts the checkout knows
SymbolPredicate
NThe customer is new
RThe customer was referred
FThe account is flagged for promo abuse
(N ∨ R) ∧ ¬FDiscount: new or referred, and not flagged

02Group, then veto

&& groups before ||

Under the tidied code, does a new customer whose account is flagged get the discount?

Every combination of three facts can be listed: 2³ = 8 rows. This program compares the intended rule with the tidied one on each row and prints the rows where they disagree.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
for (const n of [false, true])
  for (const r of [false, true])
    for (const f of [false, true]) {
      const intended = (n || r) && !f;
      const tidied = n || (r && !f);

      if (intended !== tidied)
        console.log(`disagree new=${n} referred=${r} flagged=${f}`);
    }

TypeScript accepts n || r && !f without comment; only the parentheses say which grouping you meant.

Two rows disagree: every new and flagged account, referred or not. The pull request’s tests built flagged accounts only for returning customers, so they passed.

03Count who is affected

Count the customers, not the rows

A review needs the size of the change. Last month’s checkouts, by combination:

Checkouts by fact combination (a worked model)
N R FCheckoutsIntendedTidied
0 0 05,200nono
0 0 130nono
0 1 0640yesyes
0 1 18nono
1 0 02,100yesyes
1 0 145noyes
1 1 0310yesyes
1 1 16noyes
How many of last month’s checkouts would the tidied rule have decided differently?

04Quantify over a filtered set

Quantify over the filtered set

An order can contain any number of physical and digital items. The checkout also offers free shipping when every physical item is in stock, so its review needs a rule for a whole collection. The quantifier ranges over the physical items, not over the whole order: a gift card that has not been issued yet does not hold back a parcel. “Every member of an empty set qualifies” is true, because no member breaks it, so an order with only digital items ships free. “At least one member qualifies” over an empty set is false.

An order holds a digital gift card and a software licence. Does it ship free?

The built-in forms agree: TypeScript’s every, Rust’s all and C++’s std::all_of all return true for an empty range. A hand-written loop has to start from true and only ever move to false.

05Unknown is not false

Unknown is not false

Fraud review takes a few minutes, so at checkout the flag may not be known yet. Use three values: true, false and unknown. A pending fact matters only if it could change the answer. true ∨ unknown is true, false ∧ unknown is false and ¬unknown is unknown.

Whether the customer is new is unknown, but they were referred and the account is not flagged. Discount?

A pending fact is often stored as null. null is falsy, so !flagged is true and if (flagged) skips the veto: unknown silently becomes “not flagged”. Compare with === true and === false instead.

06Build the checkout rules

Build the checkout rules

Restore the abuse veto for both kinds of eligible customer. Next, make the delivery predicate inspect the physical items that can actually hold back a parcel. The last task returns to the discount while facts are pending: distinguish a decision already settled by known facts from one the review could still change. The complete program supplies the other working helpers for each task.

In the frontend A disabled button in Next.js and Svelte Optional

A button is enabled when the policy holds, so its disabled attribute is the policy’s negation. By De Morgan, !((N || R) && F === false) is !(N || R) || F !== false. Comparing the flag with !== false keeps the button disabled while the review is pending instead of reading null as “not flagged”. The server still enforces the rule; the button only reflects it.

Estimate.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
type Fact = boolean | null; // null while the fraud review is pending

export function ApplyDiscount({
  isNew,
  referred,
  flagged
}: {
  isNew: boolean;
  referred: boolean;
  flagged: Fact;
}) {
  // !((isNew || referred) && flagged === false), by De Morgan:
  const eligible = isNew || referred;
  const pending = eligible && flagged === null;
  const disabled = !eligible || flagged !== false;

  return (
    <button type="submit" disabled={disabled}>
      {pending
        ? "Checking your account…"
        : eligible
          ? "Apply welcome discount"
          : "Not eligible for this discount"}
    </button>
  );
}

Check this idea later
An alert fires when isProd || isStaging && errorRate > 0.05. A production service has an error rate of 0.01. Does the alert fire?
A deploy proceeds when every required check has passed. A service has no required checks. Does it proceed?
Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.