Skip to content

Instantly share code, notes, and snippets.

@ezyang
Created March 27, 2018 01:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ezyang/57076dc63f24d018d16ab55e215f7f11 to your computer and use it in GitHub Desktop.
Save ezyang/57076dc63f24d018d16ab55e215f7f11 to your computer and use it in GitHub Desktop.

Formulas which explain themselves

Your goal is to write an AnnotatedBool class which behaves like a plain boolean, but also has the ability to print out an explanation of how the boolean was computed. The class needs to support:

  • Function var(string, bool), which takes a variable name and a boolean setting
  • Operator AnnotatedBool && AnnotatedBool, which ANDs two bools together
  • Operator AnnotatedBool || AnnotatedBool, which ORs two bools together
  • Implicit conversion to bool, which gives the concrete boolean value of the expression
  • Method explain(), which returns an HTML string which explains how the boolean value of the expression was computed

For example:

AnnotatedBool ab = var("a", true) && (var("c", false) || var("b", true))
ab.bool() # returns true
ab.explain() # returns HTML like:
# AND (evaluated to TRUE)
#   - a = TRUE
#   - OR (evaluated to TRUE)
#     - c = FALSE
#     - b = TRUE

Consider this edge case:

var("a", true) && var("b", true) && var("c", true)

This should print as:

# AND (evaluated to TRUE)
#   - a = TRUE
#   - b = TRUE
#   - c = TRUE

NOT as

# AND (evaluated to TRUE)
#   - AND (evaluated to TRUE)
#     - a = TRUE
#     - b = TRUE
#   - c = TRUE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment