C++: entailment by enumerating models

Propositional logic describes the world with true/false symbols. A model assigns a value to each symbol. A knowledge base entails a query if the query is true in every model that satisfies the knowledge base.

C++
#include <iostream>

bool kb(bool a, bool b, bool c) {
  return (a || b) && (!a || c) && (!b || c);
}

template <typename Query>
bool entails(Query query) {
  for (int mask = 0; mask < 8; ++mask) {
    bool a = mask & 1, b = mask & 2, c = mask & 4;
    if (kb(a, b, c) && !query(a, b, c)) {
      return false;
    }
  }
  return true;
}

int main() {
  int models = 0;
  for (int mask = 0; mask < 8; ++mask) {
    if (kb(mask & 1, mask & 2, mask & 4)) {
      ++models;
    }
  }
  std::cout << std::boolalpha;
  std::cout << "KB models: " << models << "\n";
  std::cout << "entails C: " << entails([](bool, bool, bool c) { return c; }) << "\n";
  std::cout << "entails A: " << entails([](bool a, bool, bool) { return a; }) << "\n";
}
Read the full lesson