Logic

import it.grypho.scala.leonardo.core.*
import it.grypho.scala.leonardo.logic.*
import it.grypho.scala.leonardo.parser.Parser

val a = _Variable("a")
val b = _Variable("b")
val env = new Environment()

Connectives

The logic package provides the six connectives — And, Or, Not, Implies, Xor, Iff — as ordinary expression nodes over the shared AST. Operands are untyped _Expressions, so equations and any other domain compose freely. eval runs the Kleene/Zadeh min–max rule table (and = min, or = max, not = 1 − a) and reduces to a _Bool when the operands do:

And(_Bool(true), _Bool(false)).eval(env)
// res0: Either[_Expression, _Value] = Right(_Bool(false))

In the grammar the connectives are the word operators and, or, not, implies, xor, iff, with true/false as literals. They bind looser than =/==, with precedence (tightest to loosest) not > and > xor > or > implies > iff. implies is right-associative, and iff does not chain: a iff b iff c is a parse error rather than a guess, since the biconditional is associative in classical logic and not in a many-valued one:

Parser.parse("a or b and c").get
// res1: _Expression = Or(
//   a = _Variable("a"),
//   b = And(a = _Variable("b"), b = _Variable("c"))
// )
Parser.parse("x = 1 and y = 2").get
// res2: _Expression = And(
//   a = _Equation(lhs = _Variable("x"), rhs = _Number(1.0)),
//   b = _Equation(lhs = _Variable("y"), rhs = _Number(2.0))
// )
Parser.parse("true and false").get.eval(env)
// res3: Either[_Expression, _Value] = Right(_Bool(false))

A connective over an unbound variable stays symbolic with the operands reduced, following the library-wide dual-evaluation contract. A known operand decides what it can, on either side: true is the unit of and and the annihilator of or, so true and q is q and q or true is true; likewise q implies true is true, q implies false is not q, and true xor q is not q. The rules are sound under all three t-norm families, and only a truth-valued or symbolic other side is folded:

And(a, _Bool(true)).eval(env)
// res4: Either[_Expression, _Value] = Left(_Variable("a"))
And(a, b).eval(env)
// res5: Either[_Expression, _Value] = Left(
//   And(a = _Variable("a"), b = _Variable("b"))
// )
Xor(_Bool(true), a).eval(env)
// res6: Either[_Expression, _Value] = Left(Not(_Variable("a")))
And(a, _Bool(true)).eval(env.withBinding("a", _Bool(true)))
// res7: Either[_Expression, _Value] = Right(_Bool(true))

a iff b is the biconditional, evaluated as the conjunction of the two implications; it is the classical equivalence on {true, false}, unknown iff unknown is unknown, and under every semantics it is exactly not (a xor b):

Iff(_Bool(true), _Bool(false)).eval(env)
// res8: Either[_Expression, _Value] = Right(_Bool(false))
Iff(_Truth.Unknown, _Truth.Unknown).eval(env)
// res9: Either[_Expression, _Value] = Right(_Truth(0.5))
Iff(a, _Bool(true)).eval(env)
// res10: Either[_Expression, _Value] = Left(_Variable("a"))

And, Or, and Implies short-circuit exactly as Product.eval does on a zero operand: false and X is false — and true or X is true — without evaluating X, even when X could not reduce at all:

// 1/0 = 0 cannot reduce, but the left operand decides
And(_Bool(false), Parser.parse("1/0 = 0").get).eval(env)
// res11: Either[_Expression, _Value] = Right(_Bool(false))

Three-valued (Kleene) logic

The same connectives and the same rule table carry a third truth value, unknown — the value carrier widens, the operators do not. unknown is _Truth.Unknown, a first-class value (bindable, printable, saved by :save) sitting at degree 0.5:

Parser.parse("unknown").get
// res12: _Expression = _Truth(0.5)
Not(_Truth.Unknown).eval(env)                       // 0.5 is the negation fixpoint
// res13: Either[_Expression, _Value] = Right(_Truth(0.5))
And(_Truth.Unknown, _Truth.Unknown).eval(env)
// res14: Either[_Expression, _Value] = Right(_Truth(0.5))

The crisp cases still decide, because 0 annihilates min and 1 annihilates max — which is exactly why And/Or’s short-circuits stay valid unchanged:

And(_Bool(false), _Truth.Unknown).eval(env)         // false and unknown = false
// res15: Either[_Expression, _Value] = Right(_Bool(false))
Or(_Bool(true), _Truth.Unknown).eval(env)           // true or unknown = true
// res16: Either[_Expression, _Value] = Right(_Bool(true))
And(_Bool(true), _Truth.Unknown).eval(env)          // true and unknown = unknown
// res17: Either[_Expression, _Value] = Right(_Truth(0.5))

_Truth.of collapses the crisp endpoints back to _Bool, so every boolean pattern match keeps firing and the classical truth tables come out of the graded table unchanged — the boolean logic above is a special case, not a separate path:

_Truth.of(1.0)
// res18: _Value = _Bool(true)
_Truth.of(0.0)
// res19: _Value = _Bool(false)
And(_Bool(true), _Bool(true)).eval(env)             // a _Bool, not a _Truth
// res20: Either[_Expression, _Value] = Right(_Bool(true))

kleeneTable is the three-valued counterpart of truthTable, enumerating 3^n rows (up to 10 variables); the REPL spells it truth3:

kleeneTable(Not(a), List(a)).map((row, result) => (row("a").toString, result.map(_.toString)))
// res21: Vector[Tuple2[String, Option[String]]] = Vector(
//   ("false", Some("true")),
//   ("unknown", Some("unknown")),
//   ("true", Some("false"))
// )
leonardo> truth3 a and not a
a       | (a and (not a))
false   | false
unknown | unknown
true    | false

That last row is the point: unknown and not unknown is unknown, not false. The classical laws that fail here — complement in and/or, a implies a, and a xor a — are gated on the expression being free of _Truth degrees, so simplification never “proves” them away:

simplifyLogicFully(And(_Truth.Unknown, Not(_Truth.Unknown)))   // stays unknown
// res22: _Expression = _Truth(0.5)
simplifyLogicFully(And(a, Not(a)))                             // free variables: crisp atoms
// res23: _Expression = _Bool(false)

A free variable counts as a crisp atom — that is the documented domain restriction of simplifyLogic, toCNF, and toDNF. If a variable may hold unknown, bind it and use eval rather than simplify.

Symmetric ternary: the same logic in different digits

Symmetric ternary spells the three truth values with the digits {-1, 0, 1} — the alphabet of balanced ternary — instead of {false, unknown, true}. The two alphabets are related by the affine map t = (s + 1) / 2, so this is an encoding, not a second semantics — the rule table above is untouched:

_Truth.fromSymmetric(-1.0)
// res24: _Value = _Bool(false)
_Truth.fromSymmetric(0.0)
// res25: _Value = _Truth(0.5)
_Truth.fromSymmetric(1.0)
// res26: _Value = _Bool(true)
_Truth.toSymmetric(_Truth.Unknown)
// res27: Option[Double] = Some(0.0)

The encoding is switched on per Environment (the REPL spells it logic symmetric on). With it on, the digits are additionally read as truth values in connective positions, and the Kleene identities restate verbatim:

val sym = new Environment(Environment.DefaultPrecision, Map.empty, symmetricLogic = true)
Parser.parse("-1 and 0").get.eval(sym)     // false and unknown = false
// res28: Either[_Expression, _Value] = Right(_Bool(false))
Parser.parse("1 or 0").get.eval(sym)       // true or unknown = true
// res29: Either[_Expression, _Value] = Right(_Bool(true))
Parser.parse("0 and 0").get.eval(sym)      // unknown and unknown = unknown
// res30: Either[_Expression, _Value] = Right(_Truth(0.5))
Parser.parse("not 0").get.eval(sym)        // not unknown = unknown
// res31: Either[_Expression, _Value] = Right(_Truth(0.5))

The guard matters: with the encoding off a bare 0 is a plain number, so a connective over it stays symbolic rather than silently becoming a truth value, and ordinary arithmetic is never reinterpreted in either mode:

And(_Number(1.0), _Number(0.0)).eval(env)  // default: stays symbolic
// res32: Either[_Expression, _Value] = Left(
//   And(a = _Number(1.0), b = _Number(0.0))
// )
Parser.parse("2 * 3 + 1").get.eval(sym)    // symmetric: still just arithmetic
// res33: Either[_Expression, _Value] = Right(_Number(7.0))

Because the flag lives on the Environment, a bound variable participates too — which a purely textual encoding could not do:

And(a, _Bool(true)).eval(sym.withBinding("a", _Number(0.0)))
// res34: Either[_Expression, _Value] = Right(_Truth(0.5))

One consequence worth noting: under this encoding the digit 0 is unknown, so it counts as graded for the crisp-only gate — 0 and not 0 must not fold to false by complement:

simplifyLogicFully(And(_Number(0.0), Not(_Number(0.0))), identity, symmetric = true)
// res35: _Expression = _Truth(0.5)

At the REPL the toggle is persisted by :save, but the script always writes the word spelling, so saved sessions stay portable across the setting:

leonardo> logic symmetric on
leonardo> truth3 not a
a  | (not a)
-1 | 1
0  | 0
1  | -1

Fuzzy logic: the full [0, 1] interval

The _Truth carrier already holds any degree in [0, 1], so the fuzzy tier needs no new value type — only a way to produce degrees and a choice of how they combine. truth(x) converts a scalar degree, and is also how a graded degree prints, so it round-trips:

Parser.parse("truth(0.25)").get.eval(env)
// res36: Either[_Expression, _Value] = Right(_Truth(0.25))
_Truth.of(0.25).toString
// res37: String = "truth(0.25)"
And(_Truth.of(0.3), _Truth.of(0.7)).eval(env)     // min
// res38: Either[_Expression, _Value] = Right(_Truth(0.3))
Not(_Truth.of(0.3)).eval(env)                     // 1 - a
// res39: Either[_Expression, _Value] = Right(_Truth(0.7))

Membership functions and hedges

Membership curves map a crisp measurement into [0, 1], and the hedges reshape a degree. They evaluate to truth values, so they compose with the connectives directly — no cast at each step:

Parser.parse("trimf(2.5, 0, 5, 10)").get.eval(env)     // triangular, halfway up
// res40: Either[_Expression, _Value] = Right(_Truth(0.5))
Parser.parse("gaussmf(3, 3, 1)").get.eval(env)         // gaussian, at the mean
// res41: Either[_Expression, _Value] = Right(_Bool(true))
Parser.parse("very(0.5)").get.eval(env)                // concentration: d squared
// res42: Either[_Expression, _Value] = Right(_Truth(0.25))
Parser.parse("somewhat(0.25)").get.eval(env)           // dilation: sqrt d
// res43: Either[_Expression, _Value] = Right(_Truth(0.5))
Parser.parse("very(0.5) and somewhat(0.25)").get.eval(env)
// res44: Either[_Expression, _Value] = Right(_Truth(0.25))

The built-in set is trimf(x, a, b, c), trapmf(x, a, b, c, d), gaussmf(x, mean, sigma), sigmf(x, a, c), plus the hedges very and somewhat.

Custom membership functions

The built-in curves are a convenience, not a limit: truth(x) takes an arbitrary scalar expression, so any function of one variable is a membership curve. Here is a Cauchy bell, which is none of the four built-in shapes:

val bell = Parser.parse("truth(1 / (1 + (x - 5)^2))").get
def at(v: Double) = bell.eval(env.withBinding("x", _Number(v)))
at(5.0)     // the centre
// res45: Either[_Expression, _Value] = Right(_Bool(true))
at(4.0)     // one unit out
// res46: Either[_Expression, _Value] = Right(_Truth(0.5))
at(0.0)
// res47: Either[_Expression, _Value] = Right(_Truth(0.038461538461538464))

A custom curve is not second-class — it composes with the hedges, the connectives and defuzz exactly like a built-in one:

Parser.parse("very(truth(1 / (1 + (x - 5)^2)))").get.eval(env.withBinding("x", _Number(4.0)))
// res48: Either[_Expression, _Value] = Right(_Truth(0.25))
centroid(bell, _Variable("x"), 0.0, 10.0)
// res49: Option[Double] = Some(5.000000000000004)

At the REPL a curve is usually given a name first, and then used by that name:

leonardo> bell := truth(1 / (1 + (x - 5)^2))
leonardo> defuzz(bell, x, 0, 10)
5.0

Two rules worth knowing. First, a membership degree lives in [0, 1]: an argument outside that interval is not a degree, so the node stays symbolic rather than clamping — which is how a custom curve tells you it has left the unit interval.

Parser.parse("truth(2)").get.eval(env)     // stays symbolic, not clamped to true
// res50: Either[_Expression, _Value] = Left(_TruthOf(_Number(2.0)))

Second, defuzz also accepts a bare scalar curve with no truth(...) wrapper, and either way only points inside [0, 1] count as membership:

Parser.parse("defuzz(1 / (1 + (x - 5)^2), x, 0, 10)").get.eval(env)
// res51: Either[_Expression, _Value] = Right(_Number(5.000000000000004))

Aggregating curves

Because degrees are truth values, curves combine with the ordinary connectives — the usual fuzzy-inference step, where each rule contributes a curve and the results are unioned before defuzzifying:

Parser.parse("defuzz(trimf(x, 0, 3, 6) or trimf(x, 4, 7, 10), x, 0, 10)").get.eval(env)
// res52: Either[_Expression, _Value] = Right(_Number(4.999999999999999))

The connectives are admitted in the membership positions specifically — the argument of defuzz, very, and somewhat. Ordinary function arguments stay arithmetic, so sin(a and b) is still a parse error.

Alternative t-norms

Which t-norm combines degrees is an Environment parameter, not a separate package or node: min–max (the default), product, or Łukasiewicz. All three agree with classical logic on the crisp values, so the boolean and three-valued tiers are unaffected:

val prod  = new Environment(Environment.DefaultPrecision, Map.empty, false, LogicSemantics.Product)
val lukas = new Environment(Environment.DefaultPrecision, Map.empty, false, LogicSemantics.Lukasiewicz)
And(_Truth.of(0.3), _Truth.of(0.5)).eval(prod)    // 0.3 * 0.5
// res53: Either[_Expression, _Value] = Right(_Truth(0.15))
Or(_Truth.of(0.3), _Truth.of(0.5)).eval(prod)     // a + b - a*b
// res54: Either[_Expression, _Value] = Right(_Truth(0.65))
And(_Truth.of(0.8), _Truth.of(0.7)).eval(lukas)   // max(0, 1.5 - 1)
// res55: Either[_Expression, _Value] = Right(_Truth(0.5))
And(_Bool(true), _Bool(true)).eval(lukas)         // crisp: unchanged
// res56: Either[_Expression, _Value] = Right(_Bool(true))

Only min–max is a lattice, so idempotence and absorption hold for graded degrees there alone — a and a is a squared under the product t-norm. Simplification gates those two rules on the semantics accordingly, on top of the crisp-only gate above:

simplifyLogicFully(And(_Truth.of(0.3), _Truth.of(0.3)), identity, false, LogicSemantics.MinMax)
// res57: _Expression = _Truth(0.3)
simplifyLogicFully(And(_Truth.of(0.3), _Truth.of(0.3)), identity, false, LogicSemantics.Product)
// res58: _Expression = _Truth(0.09)

Defuzzification

Defuzzifying collapses a membership curve back to one crisp value. centroid (the centre of gravity) is what defuzz(e, v, lo, hi) uses in the grammar; a fifth argument chooses another method — mom for the mean of the maxima, bisector for the point that splits the area — and meanOfMaxima and bisector are the library functions behind them:

val tri = Parser.parse("trimf(x, 0, 5, 10)").get
// tri: _Expression = TriMF(
//   x = _Variable("x"),
//   a = _Number(0.0),
//   b = _Number(5.0),
//   c = _Number(10.0)
// )
centroid(tri, _Variable("x"), 0.0, 10.0)
// res59: Option[Double] = Some(4.999999999999998)
meanOfMaxima(tri, _Variable("x"), 0.0, 10.0)
// res60: Option[Double] = Some(5.0)
Parser.parse("defuzz(trimf(x, 0, 5, 10), x, 0, 10)").get.eval(env)
// res61: Either[_Expression, _Value] = Right(_Number(4.999999999999998))
Parser.parse("defuzz(trapmf(x, 0, 2, 4, 10), x, 0, 10, mom)").get.eval(env)
// res62: Either[_Expression, _Value] = Right(_Number(3.0))

The method words are matched only in that last slot, so mom and bisector stay usable as variable names everywhere else.

Sampling takes scalar.compile’s fast path when the curve is pure scalar arithmetic and falls back to tree evaluation for membership and connective nodes — this is where logic gains its scalar import, the same relationship matrix already has.

Simplification

simplifyLogic (and its fixpoint simplifyLogicFully) applies constant folding, double negation, idempotence, complement, and absorption:

simplifyLogicFully(And(a, _Bool(true)))
// res63: _Expression = _Variable("a")
simplifyLogicFully(Not(Not(a)))
// res64: _Expression = _Variable("a")
simplifyLogicFully(Or(a, And(a, b)))
// res65: _Expression = _Variable("a")
simplifyLogicFully(And(a, Not(a)))
// res66: _Expression = _Bool(false)

Three more laws shrink a formula and so belong here: the combining law (a and b) or (a and not b) = a with its dual, the absorbed implication (a implies b) and a = a and b, and De Morgan where it removes a negation — not (not a and not b) is a or b. not (a and b) has nothing to remove and stays, as does the reshaping of implies/xor/iff, which belongs to the normal forms below. The combining law and the absorbed implication hold only in classical logic (at a = 0.9, b = 0.5 the first is 0.5, not 0.9), so like the complement law they are gated on the operands being crisp; De Morgan holds in all three t-norm families and fires unconditionally:

simplifyLogicFully(Not(And(Not(a), Not(b))))
// res67: _Expression = Or(a = _Variable("a"), b = _Variable("b"))
simplifyLogicFully(Or(And(a, b), And(a, Not(b))))
// res68: _Expression = _Variable("a")
simplifyLogicFully(And(Implies(a, b), a))
// res69: _Expression = And(a = _Variable("a"), b = _Variable("b"))
simplifyLogicFully(Or(And(_Truth.of(0.9), b), And(_Truth.of(0.9), Not(b))))   // graded: left alone
// res70: _Expression = Or(
//   a = And(a = _Truth(0.9), b = _Variable("b")),
//   b = And(a = _Truth(0.9), b = Not(_Variable("b")))
// )
simplifyLogicFully(Not(Iff(a, b)))                                              // not (a iff b) = a xor b
// res71: _Expression = Xor(a = _Variable("a"), b = _Variable("b"))

The REPL’s simplify command runs this pass after the scalar pass, injecting scalar.simplifyFully for scalar bodies nested inside connectives.

Normal forms

toCNF / toDNF rewrite an expression into conjunctive / disjunctive normal form: implies/xor/iff are desugared, not is pushed to the leaves via De Morgan’s laws, and the appropriate connective is distributed. A distribution that would exceed 1024 clauses returns the input unchanged:

toCNF(Not(And(a, b)))
// res72: _Expression = Or(a = Not(_Variable("a")), b = Not(_Variable("b")))
toCNF(Implies(a, b))
// res73: _Expression = Or(a = Not(_Variable("a")), b = _Variable("b"))
toDNF(And(a, Or(b, _Variable("c"))))
// res74: _Expression = Or(
//   a = And(a = _Variable("a"), b = _Variable("b")),
//   b = And(a = _Variable("a"), b = _Variable("c"))
// )
toCNF(Or(a, Not(a)))
// res75: _Expression = _Bool(true)

These algorithms are crisp-only: they treat non-connective sub-expressions as opaque atoms and are valid for boolean operands only.

At the prompt they are the functions cnf(e) and dnf(e), so a normal form composes inside an expression and survives :save. Where the library functions hand their input back — a graded truth value, or a distribution past the clause budget — the prompt form stays as written instead, since an input returned unchanged cannot be told from one that was already in normal form:

> cnf(a xor b)
((a or b) and ((not b) or (not a)))
> dnf((a or b) and not a)
(b and (not a))

Minimal forms

toCNF/toDNF drop duplicates and trivial clauses and stop there, so dnf((p or q) and (not p or r)) keeps a third term, the consensus of the other two. A minimal two-level form is a different question — the Karnaugh-map exercise — and minimalForm answers it by Quine–McCluskey and an exact minimum cover of the prime implicants: the fewest terms, then the fewest literals. At the prompt it is mindnf(e) and mincnf(e):

minimalForm(Parser.parse("(p or q) and (not p or r)").get, conjunctive = false)
// res76: Either[MinimiseFailure, MinimalForm] = Right(
//   MinimalForm(
//     expr = Or(
//       a = And(a = _Variable("p"), b = _Variable("r")),
//       b = And(a = Not(_Variable("p")), b = _Variable("q"))
//     ),
//     count = 1L
//   )
// )
minimalForm(Parser.parse("(p or q) and (not p or r)").get, conjunctive = true)
// res77: Either[MinimiseFailure, MinimalForm] = Right(
//   MinimalForm(
//     expr = And(
//       a = Or(a = _Variable("p"), b = _Variable("q")),
//       b = Or(a = Not(_Variable("p")), b = _Variable("r"))
//     ),
//     count = 1L
//   )
// )
minimalForm(Parser.parse("p or not p").get, conjunctive = false)
// res78: Either[MinimiseFailure, MinimalForm] = Right(
//   MinimalForm(expr = _Bool(true), count = 1L)
// )

Three points are decided, not defaulted. A cyclic cover has several minimal forms, equal in terms and literals; one is answered — the first in a fixed canonical order, terms compared literal by literal over the atoms in order of their printed form, a positive literal before a negative one — so the answer is identical on the JVM and in the browser, and count says how many there are (here two, {ab, a'c', b'c} and {a'b', bc', ac}):

val cyclic = Parser.parse("(not a and not b) or (not a and not c) or (not b and c) or (b and not c) or (a and c) or (a and b)").get
// cyclic: _Expression = Or(
//   a = Or(
//     a = Or(
//       a = Or(
//         a = Or(
//           a = And(a = Not(_Variable("a")), b = Not(_Variable("b"))),
//           b = And(a = Not(_Variable("a")), b = Not(_Variable("c")))
//         ),
//         b = And(a = Not(_Variable("b")), b = _Variable("c"))
//       ),
//       b = And(a = _Variable("b"), b = Not(_Variable("c")))
//     ),
//     b = And(a = _Variable("a"), b = _Variable("c"))
//   ),
//   b = And(a = _Variable("a"), b = _Variable("b"))
// )
minimalForm(cyclic, conjunctive = false)
// res79: Either[MinimiseFailure, MinimalForm] = Right(
//   MinimalForm(
//     expr = Or(
//       a = Or(
//         a = And(a = _Variable("a"), b = _Variable("b")),
//         b = And(a = Not(_Variable("a")), b = Not(_Variable("c")))
//       ),
//       b = And(a = Not(_Variable("b")), b = _Variable("c"))
//     ),
//     count = 2L
//   )
// )

An atom is any subexpression that is not a connective, as it is for cnf and dnf, so a relation is one atom: mindnf(x > 0 and y) answers. And the search is bounded: past 15 atoms (Limit.MaxMinimiseVars, a cube packing into one Int) or when the work outruns Limit.MaxMinimiseWork — choosing a minimum cover is NP-hard, and counting every minimal cover costs more still: measured, a random function of 8 atoms needs about thirty million units against a default of five million, so a random function of seven or eight atoms is declined with the reason while every textbook size (up to six atoms) answers in under a hundred thousand. A graded truth value is declined too, since a two-level form is a two-valued notion:

minimalForm(Parser.parse("truth(0.3) and p").get, conjunctive = false)
// res80: Either[MinimiseFailure, MinimalForm] = Left(Graded)

The search itself keeps every minimal cover, to count them, so it uses no shortcut that could drop one: a dominated column is kept, and the bound prunes only what is strictly dearer. Don’t-care sets and multi-output minimisation are not offered.

Equivalence

== between two formulas compares values, and a connective is not even an operand of it; whether two formulas say the same thing is a different relation. equivalent(f, g) answers it: true when the two agree on every assignment of their free names as booleans, false as soon as one row differs. A name bound in the session is read as its value and is not enumerated. It is crisp only, like cnf: past the table’s 16 names, or on a row that is no boolean (a graded value, a relation — names are enumerated as booleans, so x > 0 has no row), the call stays as written and a note says why. detailed carries the first differing row, in the order of truthTable:

_Equivalent(Implies(a, b), Or(Not(a), b)).eval(env)
// res81: Either[_Expression, _Value] = Right(_Bool(true))
_Equivalent(And(a, b), Or(a, b)).eval(env)
// res82: Either[_Expression, _Value] = Right(_Bool(false))
_Equivalent(And(a, b), Or(a, b)).detailed(env)
// res83: Either[EquivalenceFailure, EquivalenceVerdict] = Right(
//   Differ(
//     assignment = Map("a" -> false, "b" -> true),
//     left = false,
//     right = true
//   )
// )
_Equivalent(a, _Truth.Unknown).detailed(env)
// res84: Either[EquivalenceFailure, EquivalenceVerdict] = Left(NotBoolean)

At the prompt a differing pair names its row:

> equivalent(p and q, p or q)
false
  note: equivalent: not equivalent at p = false, q = true (the left side is false, the right side is true)

Truth tables

truthTable enumerates every boolean assignment of a variable list (up to 16 variables) and evaluates the expression under each; rows that cannot reduce to a boolean yield None:

truthTable(Xor(a, b), List(a, b))
// res85: Vector[Tuple2[Map[String, Boolean], Option[Boolean]]] = Vector(
//   (Map("a" -> false, "b" -> false), Some(false)),
//   (Map("a" -> false, "b" -> true), Some(true)),
//   (Map("a" -> true, "b" -> false), Some(true)),
//   (Map("a" -> true, "b" -> true), Some(false))
// )

The REPL command truth <expr> prints the same table over the expression’s free variables:

leonardo> truth a and b
a     b     | (a and b)
false false | false
false true  | false
true  false | false
true  true  | true

The header is the formula as typed: with f := a and b and g := a or b, truth f xor g heads its column (f xor g), not the two definitions substituted in full, while the columns are still the atoms. A row that does not reduce shows ?; when that is because a name inside a relation was enumerated as a boolean — x > 0 is not a proposition — a note names the first such operand:

leonardo> truth x > 0 or y
...
  note: truth enumerates names as booleans; x > 0.0 is not a proposition

Under pretty on a formula is written the way a logician writes it, with the fewest brackets the grammar’s precedence allows: p and q or r, not ((p and q) or r).


This site uses Just the Docs, a documentation theme for Jekyll.