Skip to content

Invariant and :reducible?

Jim Weirich edited this page May 24, 2013 · 2 revisions

Reducible Statements

In Tom's book, all statements are reducible except for the DoNothing statement. We can capture that easily in an Invariant:

describe "Statements" do
  Invariant { stmt.reducible? == ! stmt.is_a?(DoNothing) }

  describe DoNothing do
    Given(:stmt) { DoNothing.new }
    Then { stmt.to_s == "do-nothing" }
    Then { stmt == DoNothing.new }
    Then { stmt != Variable.new(:x) }
  end

  describe Assign do
    Given(:five) { Number.new(5) }
    Given(:stmt) { Assign.new(:x, five) }
    Then { stmt.to_s == "x = 5" }
    Then { stmt != DoNothing.new }
    Then { stmt == Assign.new(:x, five) }
  end

  describe If do
    Given(:condition) { LessThan.new(Number.new(0), Number.new(1)) }
    Given(:consequence) { Assign.new(:x, Number.new(0)) }
    Given(:alternative) { Assign.new(:x, Number.new(1)) }
    Given(:stmt) { If.new(condition, consequence, alternative) }

    Then { stmt.to_s == "if (0 < 1) { x = 0 } else { x = 1 }" }
  end
end

The by using a "==" in the invariant, we are saying that the definition of :reducible? is that DoNothing statements are not reducible, but everything else is. Here we can capture that logic that states truth about all Statements in one spot. Without invariants, we would have to examine each and every statement description to see what it said about the reducibility of that statement.

In the future when we add new types of statements, the invariant will ensure that the new statements will properly be reducible as well.


Return to Semantic Expression Examples