Java: forward chaining with if-then rules

A rule-based system stores facts and rules of the form: if all of these conditions hold, then this conclusion holds. Forward chaining starts with the known facts and applies any rule whose conditions are all satisfied, adding its conclusion as a new fact. It repeats until nothing new can be added.

Java
import java.util.*;

class Main {
  static class Rule {
    final List<String> body;
    final String head;

    Rule(List<String> body, String head) {
      this.body = body;
      this.head = head;
    }
  }

  public static void main(String[] args) {
    List<Rule> rules = List.of(
        new Rule(List.of("rain"), "wet"),
        new Rule(List.of("wet", "cold"), "ice"),
        new Rule(List.of("ice"), "slippery"),
        new Rule(List.of("slippery"), "careful"));
    Set<String> known = new LinkedHashSet<>(List.of("rain", "cold"));

    boolean changed = true;
    while (changed) {
      changed = false;
      for (Rule rule : rules) {
        if (known.containsAll(rule.body) && known.add(rule.head)) {
          System.out.println("derived " + rule.head);
          changed = true;
        }
      }
    }
    System.out.println(known);
  }
}
Read the full lesson