| 1 | package Logic::Relational; | ||
| 2 | |||
| 3 | 28 | ▶ | use v5.38; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 4 | 28 | ▶ | use experimental 'signatures'; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 5 | |||
| 6 | =head1 NAME | ||
| 7 | |||
| 8 | Logic::Relational - A pure-Perl relational logic system. | ||
| 9 | |||
| 10 | =head1 VERSION | ||
| 11 | |||
| 12 | Version 0.03 | ||
| 13 | |||
| 14 | =cut | ||
| 15 | |||
| 16 | 28 | our $VERSION = '0.03'; | |
| 17 | |||
| 18 | =head1 SYNOPSIS | ||
| 19 | |||
| 20 | use v5.38; | ||
| 21 | use Logic::Relational::Syntax; | ||
| 22 | |||
| 23 | # Declare a logic database/"knowledgebase" | ||
| 24 | logic Family { | ||
| 25 | # Single fact assertion | ||
| 26 | fact parent('Alice', 'Bob'); | ||
| 27 | |||
| 28 | # Grouped facts block assertion | ||
| 29 | facts { | ||
| 30 | parent('Alice', 'Charlie'); | ||
| 31 | parent('Bob', 'Diana'); | ||
| 32 | parent('Bob', 'Edward'); | ||
| 33 | parent('Edward', 'Fran'); | ||
| 34 | parent('Fran', 'George'); | ||
| 35 | parent('Heather', 'Edward'); | ||
| 36 | } | ||
| 37 | |||
| 38 | # Rule: $g is grandparent of $c IF $g is parent of $p AND $p is parent of $c | ||
| 39 | rule grandparent($g, $c) { | ||
| 40 | fresh my $p; | ||
| 41 | parent($g, $p); | ||
| 42 | parent($p, $c); | ||
| 43 | } | ||
| 44 | |||
| 45 | # "Ancestor" rule | ||
| 46 | # Base case: A parent is an ancestor | ||
| 47 | rule ancestor($c, $d) { | ||
| 48 | parent($c, $d); | ||
| 49 | } | ||
| 50 | |||
| 51 | # Recursive case: $c is ancestor of $d if $c is parent of $p AND $p is ancestor of $d | ||
| 52 | rule ancestor($c, $d) { | ||
| 53 | fresh my $p; | ||
| 54 | parent($c, $p); | ||
| 55 | ancestor($p, $d); | ||
| 56 | } | ||
| 57 | } | ||
| 58 | |||
| 59 | # Query: "Who are the children of Alice?" | ||
| 60 | query Family::parent('Alice', fresh my $child) -> my $q1; | ||
| 61 | |||
| 62 | while (my $sol = $q1->next) { | ||
| 63 | say "Alice is parent of: " . $sol->value($child); | ||
| 64 | } | ||
| 65 | |||
| 66 | # Query: "Who are the grandchildren of Alice?" | ||
| 67 | query Family::grandparent('Alice', fresh my $grandchild) -> my $q2; | ||
| 68 | |||
| 69 | while ( my $sol = $q2->next ) { | ||
| 70 | say "Alice is grandparent of: " . $sol->value($grandchild); | ||
| 71 | } | ||
| 72 | |||
| 73 | # Query: "Who are the parents of Edward?" | ||
| 74 | query Family::parent(fresh my $parent, 'Edward') -> my $q3; | ||
| 75 | |||
| 76 | while (my $sol = $q3->next) { | ||
| 77 | say "A parent of Edward is: " . $sol->value($parent); | ||
| 78 | } | ||
| 79 | |||
| 80 | # Query: "Who are the ancestors of George?" | ||
| 81 | query Family::ancestor(fresh my $ancestor, 'George') -> my $q4; | ||
| 82 | |||
| 83 | while (my $sol = $q4->next) { | ||
| 84 | say "An ancestor of George is: " . $sol->value($ancestor); | ||
| 85 | } | ||
| 86 | |||
| 87 | =head1 DESCRIPTION | ||
| 88 | |||
| 89 | C<Logic::Relational> provides a relational logic engine in pure Perl, offering logical variables, structural unification, facts, rules, and backtracking depth-first search. | ||
| 90 | |||
| 91 | It is most straightforwardly used with its syntax layer, L<Logic::Relational::Syntax>, which provides a hybrid Perl/Prolog-like syntax. | ||
| 92 | |||
| 93 | Various examples are in the "examples" folder. | ||
| 94 | |||
| 95 | =head1 USAGE | ||
| 96 | |||
| 97 | Instead of writing functions that calculate outputs from inputs, declare relations between terms. In a relation, there are no fixed "inputs" or "outputs". A relation simply describes a logical truth that holds between values. Relations are declared in a logic database which can then be queried. | ||
| 98 | |||
| 99 | =head2 Atoms, Variables and Structured Data | ||
| 100 | |||
| 101 | I<Atoms> are concrete scalar values such as strings ('Alice') or numbers (42). | ||
| 102 | |||
| 103 | I<Logical variables> are declared with C<fresh my $var;> or inside C<rule> signatures. Unlike Perl scalars which store fixed values, an unbound logical variable represents a placeholder that can be unified with any term. | ||
| 104 | |||
| 105 | I<Structured data objects> are represented as I<compound terms> consisting of a functor name and positional arguments. Compound terms are created using C<< term( functor => @arguments ) >>. | ||
| 106 | |||
| 107 | =head2 Facts, Rules, Goals and Backtracking | ||
| 108 | |||
| 109 | I<Facts> declare relations between atoms. | ||
| 110 | |||
| 111 | I<Rules> allow you to infer new facts from existing ones. A rule states: C<"Head is true IF Body goals are true">. | ||
| 112 | |||
| 113 | When evaluating rules, the engine performs depth-first backtracking search. If a rule path leads to failure, the engine automatically backtracks to the previous choice point and tries alternative facts or rules. | ||
| 114 | |||
| 115 | C<true_goal> provides a goal that always succeeds. C<fail_goal> provides a goal that forces failure and backtracking. | ||
| 116 | |||
| 117 | =head2 Query execution | ||
| 118 | |||
| 119 | To execute a query on a logic database, use the name of the logic database with the fact or rule to query, substituting logic variables to be bound as required. The query will return an iterator object that will yield solutions. | ||
| 120 | |||
| 121 | # Execute a query and assign iterator | ||
| 122 | query Family::grandparent('Alice', fresh my $child) -> my $q; | ||
| 123 | |||
| 124 | # Option A: Step through solutions with iterator | ||
| 125 | while (my $sol = $q->next) { | ||
| 126 | say "Grandchild: " . $sol->value($child); | ||
| 127 | } | ||
| 128 | |||
| 129 | # Option B: Collect all solution objects directly (list or arrayref) | ||
| 130 | my @sols = $q->all( limit => 100 ); # default limit: 10,000 | ||
| 131 | |||
| 132 | # Option C: Extract all reified values bound to a variable directly | ||
| 133 | my @grandchildren = $q->all_values($child); | ||
| 134 | |||
| 135 | # Option D: Extract deduplicated values bound to a variable | ||
| 136 | my @unique_grandchildren = $q->distinct_values($child); | ||
| 137 | |||
| 138 | # Option E: Extract tuples of multiple variables (deduplicated by default) | ||
| 139 | query Family::parent(fresh my $p, fresh my $c) -> my $q_pairs; | ||
| 140 | my @pairs = $q_pairs->all_tuples([$p, $c]); | ||
| 141 | |||
| 142 | =head2 Unification | ||
| 143 | |||
| 144 | Unification attempts to make two terms identical by finding a suitable set of variable bindings. If the terms cannot be unified, it returns C<undef>, allowing the search engine to backtrack cleanly without side effects. Use C<unify($x, $y)> or equivalent syntax C<$x := $y>. | ||
| 145 | |||
| 146 | There are unification-style tests available which do not bind variables: | ||
| 147 | |||
| 148 | =over 4 | ||
| 149 | |||
| 150 | =item * | ||
| 151 | |||
| 152 | C<$x == $y;> B<Strict identity>. Tests if terms are currently syntactically identical without mutating variables. | ||
| 153 | |||
| 154 | =item * | ||
| 155 | |||
| 156 | C<$x \== $y;> B<Strict Non-Identity>. Succeeds if terms are not syntactically identical. | ||
| 157 | |||
| 158 | =item * | ||
| 159 | |||
| 160 | C<$x !:= $y;> B<Non-Unifiability>. Fails if C<$x> and C<$y> I<can> unify. | ||
| 161 | |||
| 162 | =back | ||
| 163 | |||
| 164 | When two terms are unified, the engine executes a recursive structural comparison following these rules: | ||
| 165 | |||
| 166 | =over 2 | ||
| 167 | |||
| 168 | =item 1. Variable Dereferencing ("Walking") | ||
| 169 | |||
| 170 | Before comparing any two terms, both terms are dereferenced ("walked") through the current substitution environment. If a variable C<$X> was previously bound to C<'Alice'>, the unifier evaluates C<'Alice'> rather than the raw variable object. | ||
| 171 | |||
| 172 | =item 2. Unbound Logical Variables and the Occurs Check | ||
| 173 | |||
| 174 | If an unbound variable C<$X> is unified with another term C<$T>: | ||
| 175 | |||
| 176 | =over 4 | ||
| 177 | |||
| 178 | =item * | ||
| 179 | |||
| 180 | If C<$T> is the exact same variable C<$X>, unification succeeds with no changes. | ||
| 181 | |||
| 182 | =item * | ||
| 183 | |||
| 184 | If C<$T> is another unbound variable C<$Y>, C<$X> and C<$Y> become aliased so that binding one in the future automatically binds the other. | ||
| 185 | |||
| 186 | =item * | ||
| 187 | |||
| 188 | If C<$T> is a concrete term, C<$X> is bound to C<$T>, provided that C<$T> does not contain C<$X>. The engine performs a strict B<occurs check> to prevent circular infinite structures (such as C<$X = f($X)>). | ||
| 189 | |||
| 190 | =back | ||
| 191 | |||
| 192 | =item 3. Compound Terms and Native Data Structures | ||
| 193 | |||
| 194 | =over 4 | ||
| 195 | |||
| 196 | =item * | ||
| 197 | |||
| 198 | B<Compound Terms:> Two terms C<f(A1, A2)> and C<g(B1, B2)> unify if and only if their functors are identical (C<f eq g>), their arities match, and all corresponding arguments unify pairwise. | ||
| 199 | |||
| 200 | =item * | ||
| 201 | |||
| 202 | B<Native Perl Arrays:> Arrays unify element-by-element. Tail matching via C<rest($tail)> allows list destructuring (e.g. unifying C<[$head, rest($tail)]> with C<[1, 2, 3]> binds C<$head = 1> and C<$tail = [2, 3]>). | ||
| 203 | |||
| 204 | =item * | ||
| 205 | |||
| 206 | B<Native Perl Hashes:> Hashes unify by key. Unifying C<={ id => $id, _ => rest($r) }> with a payload matches specified keys while capturing optional remaining key/value pairs into C<$r>. C<slurp> can be used as an alias for C<rest> if preferred. | ||
| 207 | |||
| 208 | =back | ||
| 209 | |||
| 210 | =item 4. Atomic Values and Plain Scalars | ||
| 211 | |||
| 212 | Plain scalars (strings, numbers) and L<Logic::Relational::Atom> objects unify if and only if their string representations are identical under standard Perl string equality. | ||
| 213 | |||
| 214 | =back | ||
| 215 | |||
| 216 | =head2 List processing | ||
| 217 | |||
| 218 | Lists can be decomposed into their first element (C<$head>) and the remaining tail list (C<$tail>) using C<[$head, rest($tail)]> (C<slurp> is an equivalent syntax to C<rest> if preferred). For example:- | ||
| 219 | |||
| 220 | use v5.38; | ||
| 221 | use Logic::Relational::Syntax; | ||
| 222 | |||
| 223 | logic ListRules { | ||
| 224 | # Base case: $x is the head of the list | ||
| 225 | rule list_member($x, [$x, rest($tail)]) { | ||
| 226 | true_goal; | ||
| 227 | } | ||
| 228 | |||
| 229 | # Recursive case: $x is in the tail of the list | ||
| 230 | rule list_member($x, [$y, rest($tail)]) { | ||
| 231 | list_member($x, $tail); | ||
| 232 | } | ||
| 233 | } | ||
| 234 | |||
| 235 | query ListRules::list_member('C', ['A', 'B', 'C', 'D', 'E']) -> my $q; | ||
| 236 | if ( $q->next ) { | ||
| 237 | say "'C' is a member of list ['A', 'B', 'C', 'D', 'E']"; | ||
| 238 | } | ||
| 239 | else { | ||
| 240 | say "'C' is not a member of list ['A', 'B', 'C', 'D', 'E']"; | ||
| 241 | } | ||
| 242 | |||
| 243 | =head2 Built-in relations | ||
| 244 | |||
| 245 | Some commonly-used relations are built-in and are automatically available through a logic block. See C<stdlib_demo.pl> in the examples. | ||
| 246 | |||
| 247 | =over 4 | ||
| 248 | |||
| 249 | =item * | ||
| 250 | |||
| 251 | C<append($l1, $l2, $out)> - List concatenation and splitting e.g. C<append([1,2], [3,4], $res)> | ||
| 252 | |||
| 253 | =item * | ||
| 254 | |||
| 255 | C<member($elem, $list)> - List membership and element generation e.g. C<member($x, ['a', 'b', 'c'])> | ||
| 256 | |||
| 257 | =item * | ||
| 258 | |||
| 259 | C<not_member($elem, $list)> - List non-membership (unification check) e.g. C<not_member('x', ['a', 'b', 'c'])> | ||
| 260 | |||
| 261 | =item * | ||
| 262 | |||
| 263 | C<length($list, $len)> - Relates a list to its integer length e.g. C<length([10, 20], $len)> | ||
| 264 | |||
| 265 | =item * | ||
| 266 | |||
| 267 | C<reverse($list, $rev)> - Reverses a list relationally e.g. C<reverse([1, 2, 3], $rev)> | ||
| 268 | |||
| 269 | =item * | ||
| 270 | |||
| 271 | C<select($elem, $list, $rest)> - Removes or inserts an element e.g. C<select('b', ['a','b','c'], $rest)> | ||
| 272 | |||
| 273 | =item * | ||
| 274 | |||
| 275 | C<permutation($list, $perm)> - Generates list permutations e.g. C<permutation([1, 2], $perm)> | ||
| 276 | |||
| 277 | =item * | ||
| 278 | |||
| 279 | C<between($low, $high, $val)> - Backtracking integer generator e.g. C<between(1, 10, $val)> | ||
| 280 | |||
| 281 | =item * | ||
| 282 | |||
| 283 | C<succ($x, $y)> - Successor relation (y = x + 1) e.g. C<succ(5, $next)> | ||
| 284 | |||
| 285 | =item * | ||
| 286 | |||
| 287 | C<min($x, $y, $min)> - Relational minimum e.g. C<min(10, 20, $m)> | ||
| 288 | |||
| 289 | =item * | ||
| 290 | |||
| 291 | C<max($x, $y, $max)> - Relational maximum e.g. C<max(10, 20, $m)> | ||
| 292 | |||
| 293 | =back | ||
| 294 | |||
| 295 | |||
| 296 | =head2 Arithmetic binding | ||
| 297 | |||
| 298 | To perform mathematical calculations once variables become ground (bound to concrete values), use the arithmetic evaluation operator "is": (C<< $var is <expr>; >>). For example, C<$n1 is $n - 1;> evaluates C<$n - 1> once C<$n> is bound, and unifies the result with C<$n1>. | ||
| 299 | |||
| 300 | =head2 Constraint Logic Programming (CLP(FD)) | ||
| 301 | |||
| 302 | There is some support for Constraint Logic Programming over Finite Domains, which is useful for certain problems. | ||
| 303 | |||
| 304 | CLP(FD) operates in three phases: | ||
| 305 | |||
| 306 | =over 4 | ||
| 307 | |||
| 308 | =item 1. | ||
| 309 | |||
| 310 | B<Domain Declaration>: Constrain variables to integer ranges using C<$var in MIN..MAX;> or to a discrete list of integers using C<$var in [1, 4, 9, 16];>. | ||
| 311 | |||
| 312 | =item 2. | ||
| 313 | |||
| 314 | B<Constraint Network>: Assert relationships (such as C<all_different($x, $y, $z)>). | ||
| 315 | |||
| 316 | =item 3. | ||
| 317 | |||
| 318 | B<Labeling / Instantiation>: Trigger backtracking search using C<label($x, $y, $z)>. | ||
| 319 | |||
| 320 | =back | ||
| 321 | |||
| 322 | CLP(FD) arithmetic constraints (C<< #= >>, C<< #< >>, C<< #> >>, C<< #<= >>, C<< #>= >>, C<< #/= >>) allow mathematical relationships to be asserted on unbound domain variables before and during search. | ||
| 323 | |||
| 324 | use v5.38; | ||
| 325 | use Logic::Relational::Syntax; | ||
| 326 | |||
| 327 | # 3x3 Magic Square solver using declarative CLP(FD) arithmetic constraints (#=) | ||
| 328 | logic MagicCLPFD { | ||
| 329 | |||
| 330 | rule solve($square) { | ||
| 331 | |||
| 332 | # Declare cells and constrain their integer domain to 1..9 | ||
| 333 | fresh my ( $m11, $m12, $m13, $m21, $m22, $m23, $m31, $m32, $m33 ) in 1..9; | ||
| 334 | |||
| 335 | # Output square structure | ||
| 336 | $square := [ $m11, $m12, $m13, $m21, $m22, $m23, $m31, $m32, $m33 ]; | ||
| 337 | |||
| 338 | # Constraint 1: All cells must be distinct | ||
| 339 | all_different( $m11, $m12, $m13, $m21, $m22, $m23, $m31, $m32, $m33 ); | ||
| 340 | |||
| 341 | # Constraint 2: Declarative CLP(FD) row sum constraints (#=) | ||
| 342 | $m11 + $m12 + $m13 #= 15; | ||
| 343 | $m21 + $m22 + $m23 #= 15; | ||
| 344 | $m31 + $m32 + $m33 #= 15; | ||
| 345 | |||
| 346 | # Constraint 3: Declarative CLP(FD) column sum constraints (#=) | ||
| 347 | $m11 + $m21 + $m31 #= 15; | ||
| 348 | $m12 + $m22 + $m32 #= 15; | ||
| 349 | $m13 + $m23 + $m33 #= 15; | ||
| 350 | |||
| 351 | # Constraint 4: Declarative CLP(FD) diagonal sum constraints (#=) | ||
| 352 | $m11 + $m22 + $m33 #= 15; | ||
| 353 | $m31 + $m22 + $m13 #= 15; | ||
| 354 | |||
| 355 | # Trigger backtracking search labeling | ||
| 356 | label( $m11, $m12, $m13, $m21, $m22, $m23, $m31, $m32, $m33 ); | ||
| 357 | } | ||
| 358 | } | ||
| 359 | |||
| 360 | # Run logic query | ||
| 361 | query MagicCLPFD::solve( fresh my $sol )->my $q; | ||
| 362 | |||
| 363 | my $count = 0; | ||
| 364 | while ( my $s = $q->next ) { | ||
| 365 | $count++; | ||
| 366 | my $p = $s->value($sol); | ||
| 367 | say "Solution #$count:\n"; | ||
| 368 | say "+---+---+---+"; | ||
| 369 | say "| $p->[0] | $p->[1] | $p->[2] |"; | ||
| 370 | say "+---+---+---+"; | ||
| 371 | say "| $p->[3] | $p->[4] | $p->[5] |"; | ||
| 372 | say "+---+---+---+"; | ||
| 373 | say "| $p->[6] | $p->[7] | $p->[8] |"; | ||
| 374 | say "+---+---+---+\n"; | ||
| 375 | } | ||
| 376 | |||
| 377 | =head3 Unification in CLP(FD) | ||
| 378 | |||
| 379 | If a domain-constrained variable C<$X> (e.g. C<$X in [1..5]>) is unified with another domain variable C<$Y> (e.g. C<$Y in [3..8]>), the unifier computes the set intersection of their domains (C<[3..5]>). If the resulting domain is empty, unification fails. If the intersection leaves a single value, the variable is automatically bound to that scalar. | ||
| 380 | |||
| 381 | =head2 Disjunction blocks | ||
| 382 | |||
| 383 | Disjunction (OR) represents branching choice points. While defining multiple C<rule>s with the same name creates top-level disjunction, you can create inline choice points inside a single rule body using C<either { ... } or { ... }>. Any number of C<or { ... }> blocks can follow an C<either { ... }> | ||
| 384 | |||
| 385 | logic AccessControl { | ||
| 386 | rule valid_user($user, $role) { | ||
| 387 | user_account($user, $role); | ||
| 388 | either { | ||
| 389 | unify($role, 'admin'); | ||
| 390 | } | ||
| 391 | or { | ||
| 392 | unify($role, 'editor'); | ||
| 393 | } | ||
| 394 | or { | ||
| 395 | unify($role, 'moderator'); | ||
| 396 | } | ||
| 397 | } | ||
| 398 | } | ||
| 399 | |||
| 400 | =head2 Negation-as-Failure | ||
| 401 | |||
| 402 | Negation is implemented as Negation-as-Failure. Therefore, C<not { Goal }> succeeds if C<Goal> fails, and fails if C<Goal> succeeds. | ||
| 403 | |||
| 404 | logic Security { | ||
| 405 | fact banned_ip('192.168.1.50'); | ||
| 406 | fact banned_ip('10.0.0.99'); | ||
| 407 | |||
| 408 | # Access is allowed if IP is NOT banned | ||
| 409 | rule allow_access($ip) { | ||
| 410 | not { | ||
| 411 | banned_ip($ip); | ||
| 412 | } | ||
| 413 | } | ||
| 414 | } | ||
| 415 | |||
| 416 | Variables inside a C<not { ... }> block must be ground (bound to concrete values) at evaluation time. | ||
| 417 | |||
| 418 | =head2 Subgoal Tabling (Memoization) and Cycle Handling | ||
| 419 | |||
| 420 | Standard depth-first relational search can struggle with cyclic data structures (such as bidirectional social networks or transport graphs with loops) and left-recursive rules. C<Logic::Relational> provides two complementary mechanisms to handle recursion safely and efficiently: | ||
| 421 | |||
| 422 | =over 4 | ||
| 423 | |||
| 424 | =item 1. B<Automatic Ancestor Cycle Pruning (Always Active)> | ||
| 425 | |||
| 426 | During rule evaluation, the engine tracks active ancestor calls along the current derivation path. If a recursive subgoal is called with arguments that are structurally identical (up to variable renaming) to an active ancestor call on the same branch, that branch is automatically pruned. This prevents infinite loops on cyclic graphs without requiring manual "visited" lists, while still exploring every distinct simple path. Structural recursion (such as list processing with C<append> or C<member>) is unaffected because recursive calls operate on progressively smaller substructures. | ||
| 427 | |||
| 428 | =item 2. B<Subgoal Tabling / Answer Memoization (C<table>)> | ||
| 429 | |||
| 430 | Declaring a predicate as I<tabled> instructs the engine to memoize unique answers for each subgoal call signature and evaluate recursive dependencies to a least fixpoint. Tabling provides three main benefits: | ||
| 431 | |||
| 432 | =over 4 | ||
| 433 | |||
| 434 | =item * | ||
| 435 | |||
| 436 | B<Left-Recursion Support:> Rules such as C<reachable($x, $z) :- reachable($x, $y), edge($y, $z)> terminate cleanly instead of recursing infinitely. | ||
| 437 | |||
| 438 | =item * | ||
| 439 | |||
| 440 | B<Answer Deduplication:> On diamond-shaped or cyclic graphs where multiple paths lead to the same conclusion, a tabled predicate yields each unique answer only once. | ||
| 441 | |||
| 442 | =item * | ||
| 443 | |||
| 444 | B<Dynamic Programming Performance:> Repeated subgoals within a query reuse cached answers instead of recomputing derivations. | ||
| 445 | |||
| 446 | =back | ||
| 447 | |||
| 448 | Use the C<table> keyword inside a C<logic> block to enable tabling for one or more predicates by C<name/arity> (or C<name/*> for all arities): | ||
| 449 | |||
| 450 | logic Network { | ||
| 451 | table reachable/2; | ||
| 452 | |||
| 453 | facts { | ||
| 454 | edge('A', 'B'); | ||
| 455 | edge('B', 'C'); | ||
| 456 | edge('C', 'A'); # cycle | ||
| 457 | edge('C', 'D'); | ||
| 458 | } | ||
| 459 | |||
| 460 | rule reachable($x, $y) { | ||
| 461 | edge($x, $y); | ||
| 462 | } | ||
| 463 | |||
| 464 | # Left-recursive rule over a cyclic graph | ||
| 465 | rule reachable($x, $z) { | ||
| 466 | fresh my $y; | ||
| 467 | reachable($x, $y); | ||
| 468 | edge($y, $z); | ||
| 469 | } | ||
| 470 | } | ||
| 471 | |||
| 472 | my $q; | ||
| 473 | query Network::reachable('A', fresh my $node) -> $q; | ||
| 474 | my @nodes = $q->all_values($node); # ('A', 'B', 'C', 'D') | ||
| 475 | |||
| 476 | =item 3. B<Automatic Left-Recursion Detection and Auto-Tabling> | ||
| 477 | |||
| 478 | If a rule is defined with direct left-recursion (i.e. where the first body subgoal calls the exact same predicate and arity as the rule head) and the predicate has not been explicitly declared as tabled, C<Logic::Relational> will automatically enable tabling for that predicate and emit a warning via L<Carp/carp>. This prevents unintentional infinite recursion and out-of-memory errors while ensuring that the rule evaluates to its least fixpoint. | ||
| 479 | |||
| 480 | =item 4. B<Execution Fuel / Search Step Limit (C<max_steps>)> | ||
| 481 | |||
| 482 | To protect against runaway searches, unbounded recursion, and memory exhaustion, C<Logic::Relational::Query> enforces a maximum resolution step limit (default: 100,000 steps). If a query exceeds this limit, it throws an exception (via C<croak>). | ||
| 483 | |||
| 484 | The step limit can be customized or disabled: | ||
| 485 | |||
| 486 | =over 4 | ||
| 487 | |||
| 488 | =item * On the Program: C<$program-E<gt>max_steps(500_000)> or at construction C<Logic::Relational::Program-E<gt>new(max_steps =E<gt> 500_000)>. | ||
| 489 | |||
| 490 | =item * On a Query: C<$program-E<gt>query($goal, max_steps =E<gt> 500_000)>. | ||
| 491 | |||
| 492 | =item * Unlimited: specify C<max_steps =E<gt> 0> to disable step limits. | ||
| 493 | |||
| 494 | =back | ||
| 495 | |||
| 496 | =back | ||
| 497 | |||
| 498 | See C<tabling_and_cycles.pl> in the examples. | ||
| 499 | |||
| 500 | =head2 Guards | ||
| 501 | |||
| 502 | Use C<guard> to run Perl code inside a logic rule. For example:- | ||
| 503 | |||
| 504 | guard([$age, $status], sub ($a, $s) { | ||
| 505 | return $a >= 18 && $s eq 'active'; | ||
| 506 | }); | ||
| 507 | |||
| 508 | C<$vars>: Array reference of logical variables passed into the subroutine. | ||
| 509 | |||
| 510 | C<sub>: Perl subroutine that receives the reified scalar values of those variables and returns a boolean (C<1> for goal success, C<0> for failure). | ||
| 511 | |||
| 512 | =head2 Generators | ||
| 513 | |||
| 514 | Use a C<generator> to access Perl iterator subroutines. On backtracking the iterator will be called to provide the subsequent value. | ||
| 515 | |||
| 516 | logic Streams { | ||
| 517 | # Generator named fibonacci with arity 1: fibonacci(N) | ||
| 518 | generator fibonacci(1) sub ($n) { | ||
| 519 | my $f0 = 0; | ||
| 520 | my $f1 = 1; | ||
| 521 | |||
| 522 | # Returns an iterator closure that yields 1-element tuple arrayrefs | ||
| 523 | return sub { | ||
| 524 | my $curr = $f0; | ||
| 525 | $f0 = $f1; | ||
| 526 | $f1 = $curr + $f1; | ||
| 527 | return [$curr]; | ||
| 528 | }; | ||
| 529 | }; | ||
| 530 | } | ||
| 531 | |||
| 532 | query Streams::fibonacci( fresh my $val )->my $q; | ||
| 533 | |||
| 534 | my $count = 0; | ||
| 535 | while ( my $sol = $q->next ) { | ||
| 536 | # Careful: will run indefinitely if not limited | ||
| 537 | last if ++$count > 10; | ||
| 538 | say "Fibonacci #$count = " . $sol->value($val); | ||
| 539 | } | ||
| 540 | |||
| 541 | =head2 Accessing the program object | ||
| 542 | |||
| 543 | Inside any package declared with C<logic PackageName { ... }>, a package variable C<$PROGRAM> (e.g. C<$PackageName::PROGRAM>) is automatically instantiated. You can use C<$PROGRAM> to perform runtime operations, such as asserting and retracting facts:- | ||
| 544 | |||
| 545 | logic AccessControl { | ||
| 546 | fact user('alice', 28); | ||
| 547 | } | ||
| 548 | |||
| 549 | # assert a fact | ||
| 550 | $AccessControl::PROGRAM->fact( user => 'bob', 30 ); | ||
| 551 | |||
| 552 | # assert a fact and get its unique clause ID | ||
| 553 | my $clause_id = $AccessControl::PROGRAM->fact( user => 'charlie', 34 ); | ||
| 554 | |||
| 555 | # retract all facts matching the term pattern | ||
| 556 | $AccessControl::PROGRAM->retract( user => 'bob', 30 ); | ||
| 557 | |||
| 558 | # retract a fact by its specific clause id | ||
| 559 | $AccessControl::PROGRAM->retract_clause($clause_id); | ||
| 560 | |||
| 561 | # enable, check, or disable subgoal tabling at runtime | ||
| 562 | $AccessControl::PROGRAM->table('reachable/2'); | ||
| 563 | my $is_tabled = $AccessControl::PROGRAM->is_tabled('reachable/2'); | ||
| 564 | $AccessControl::PROGRAM->untable('reachable/2'); | ||
| 565 | |||
| 566 | When a query iterator is created, it operates on an immutable snapshot of the program version at that moment, meaning that assertions or retractions made mid-query will not affect running queries. | ||
| 567 | |||
| 568 | For scenarios where facts should only exist for the duration of a specific task or block (such as hypothetical reasoning or request-scoped context), use C<with_facts>: | ||
| 569 | |||
| 570 | $AccessControl::PROGRAM->with_facts( | ||
| 571 | [ | ||
| 572 | [ user => 'temp_guest', 25 ], | ||
| 573 | [ user => 'visitor', 30 ], | ||
| 574 | ], | ||
| 575 | sub { | ||
| 576 | # Inside this callback, temp_guest and visitor exist as facts | ||
| 577 | query AccessControl::user(fresh my $u, fresh my $a) -> my $q; | ||
| 578 | while (my $sol = $q->next) { | ||
| 579 | say "User: " . $sol->value($u); | ||
| 580 | } | ||
| 581 | } | ||
| 582 | ); | ||
| 583 | |||
| 584 | After the callback completes (even if an exception occurs), the temporary facts are automatically retracted. | ||
| 585 | |||
| 586 | =head2 Transactions | ||
| 587 | |||
| 588 | It is possible to wrap multiple database changes in an atomic transaction. | ||
| 589 | |||
| 590 | try { | ||
| 591 | $AccessControl::PROGRAM->transaction(sub { | ||
| 592 | # make various changes | ||
| 593 | $AccessControl::PROGRAM->fact( user => 'dave', 21 ); | ||
| 594 | |||
| 595 | # do various checks... | ||
| 596 | |||
| 597 | # If an exception is thrown, all changes inside the block are rolled back. | ||
| 598 | die "Operation aborted due to some failure"; | ||
| 599 | }); | ||
| 600 | } | ||
| 601 | catch ($e) { | ||
| 602 | say "Transaction rolled back cleanly: $e"; | ||
| 603 | } | ||
| 604 | |||
| 605 | =head2 Expiring and mutating facts | ||
| 606 | |||
| 607 | Facts can be asserted with an explicit Time-To-Live (TTL) using C<assert_fact>: | ||
| 608 | |||
| 609 | # Fact expires in 10 seconds | ||
| 610 | $AccessControl::PROGRAM->assert_fact( | ||
| 611 | term => [ session => 'alice_token', 'active' ], | ||
| 612 | expires_in => 10, | ||
| 613 | ); | ||
| 614 | |||
| 615 | # Fact expires at a specific Unix timestamp | ||
| 616 | $AccessControl::PROGRAM->assert_fact( | ||
| 617 | term => [ session => 'bob_token', 'active' ], | ||
| 618 | expires_at => time + 300, | ||
| 619 | ); | ||
| 620 | |||
| 621 | # Declarative Fact Mutation (expire_to) | ||
| 622 | # At the time of expiry, a fact can mutate | ||
| 623 | $AdventureGame::PROGRAM->assert_fact( | ||
| 624 | term => [ match_state => 'lit', 'storeroom' ], | ||
| 625 | expires_in => 10, | ||
| 626 | expire_to => [ match_state => 'burnt_out', 'storeroom' ], | ||
| 627 | ); | ||
| 628 | |||
| 629 | =head2 Monitoring | ||
| 630 | |||
| 631 | Register an observer callback to monitor insertions and retractions. | ||
| 632 | |||
| 633 | $PROGRAM->on_change(sub ($event) { | ||
| 634 | my $op = $event->operation; # 'assert' or 'retract' | ||
| 635 | my $clause = $event->clause; | ||
| 636 | say "EVENT: $op on clause " . $clause->head->as_string; | ||
| 637 | }); | ||
| 638 | |||
| 639 | To debug complex logic programs or inspect how the engine traverses search trees, attach a trace listener to a query. | ||
| 640 | |||
| 641 | query MyProgram::my_pred(fresh my $x) -> my $q; | ||
| 642 | |||
| 643 | $q->trace(sub ($event) { | ||
| 644 | my $type = $event->type; # 'call', 'exit', 'redo', 'fail' | ||
| 645 | my $goal = $event->goal; | ||
| 646 | say sprintf("TRACE [%-5s] Goal: %s", $type, $goal->as_string); | ||
| 647 | }); | ||
| 648 | |||
| 649 | while ( my $sol = $q->next ) { | ||
| 650 | say $sol->value($x) | ||
| 651 | } | ||
| 652 | |||
| 653 | =head2 Saving and Loading | ||
| 654 | |||
| 655 | Use C<save_snapshot> and C<load_snapshot> to save and load facts in a program to JSON file on disk on in memory. | ||
| 656 | |||
| 657 | # Save current dynamic facts and metadata to a JSON snapshot file | ||
| 658 | $AccessControl::PROGRAM->save_snapshot("save.json"); | ||
| 659 | |||
| 660 | # Or save directly to a scalar reference | ||
| 661 | my $json_str; | ||
| 662 | $AccessControl::PROGRAM->save_snapshot(\$json_str); | ||
| 663 | |||
| 664 | # Load snapshot back from disk (mode => 'replace' clears dynamic facts while preserving static rules) | ||
| 665 | $AccessControl::PROGRAM->load_snapshot("save.json", mode => 'replace'); | ||
| 666 | |||
| 667 | # Blend snapshot facts into existing database | ||
| 668 | $AccessControl::PROGRAM->load_snapshot("save.json", mode => 'merge'); | ||
| 669 | |||
| 670 | # Relative TTL Mode (Game / Simulation Time): Pauses expiring facts when saved, | ||
| 671 | # resuming their remaining TTL from the moment the snapshot is reloaded | ||
| 672 | $AccessControl::PROGRAM->load_snapshot("save.json", ttl_mode => 'relative'); | ||
| 673 | |||
| 674 | C<save_snapshot> exports ground facts and their metadata. When C<load_snapshot(mode => 'replace')> is called, it clears existing dynamic facts while preserving static logic C<rule> definitions compiled into the code. | ||
| 675 | |||
| 676 | =head3 TTL Modes for Expiring Facts | ||
| 677 | |||
| 678 | C<ttl_mode => 'absolute'> (default): Wall-clock time keeps ticking while saved on disk. | ||
| 679 | |||
| 680 | C<ttl_mode => 'relative'> (or C<pause_ttl => 1>): Game/simulation time pauses while saved on disk. When reloaded, expiring facts resume with their exact C<remaining_ttl> relative to the moment of loading. | ||
| 681 | |||
| 682 | =head1 SEE ALSO | ||
| 683 | |||
| 684 | L<AI::Prolog> | ||
| 685 | |||
| 686 | L<Logic::Probabilistic> | ||
| 687 | |||
| 688 | =cut | ||
| 689 | |||
| 690 | 28 | ▶ | use Logic::Relational::DSL (); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 691 | 28 | our @EXPORT_OK = @Logic::Relational::DSL::EXPORT_OK; | |
| 692 | 28 | ▶ | use parent 'Exporter'; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 693 | |||
| 694 | # Re-export symbols | ||
| 695 | 28 | for my $sym (@EXPORT_OK) { | |
| 696 | 28 | ▶ | no strict 'refs'; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 697 | 644 | *{$sym} = \&{"Logic::Relational::DSL::$sym"}; | |
| 698 | } | ||
| 699 | |||
| 700 | =head1 AUTHOR | ||
| 701 | |||
| 702 | Matt Johnson <mjohnson@affectivesilicon.com> | ||
| 703 | |||
| 704 | =head1 AI | ||
| 705 | |||
| 706 | This module was developed with assistance from various AI/LLM, specifically ChatGPT 5.5 and Gemini Flash 3.5/3.6/3.8. | ||
| 707 | |||
| 708 | =head1 BUGS | ||
| 709 | |||
| 710 | Please report any bugs or feature requests to C<bug-logic-relational at rt.cpan.org>, or through | ||
| 711 | the web interface at L<https://rt.cpan.org/NoAuth/ReportBug.html?Queue=Logic-Relational>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. | ||
| 712 | |||
| 713 | |||
| 714 | =head1 SUPPORT | ||
| 715 | |||
| 716 | You can find documentation for this module with the perldoc command. | ||
| 717 | |||
| 718 | perldoc Logic::Relational | ||
| 719 | |||
| 720 | |||
| 721 | You can also look for information at: | ||
| 722 | |||
| 723 | =over 4 | ||
| 724 | |||
| 725 | =item * RT: CPAN's request tracker (report bugs here) | ||
| 726 | |||
| 727 | L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=Logic-Relational> | ||
| 728 | |||
| 729 | =item * Search CPAN | ||
| 730 | |||
| 731 | L<https://metacpan.org/release/Logic-Relational> | ||
| 732 | |||
| 733 | =back | ||
| 734 | |||
| 735 | |||
| 736 | =head1 LICENSE AND COPYRIGHT | ||
| 737 | |||
| 738 | This software is Copyright (c) 2026 by Matt Johnson <mjohnson@affectivesilicon.com>. | ||
| 739 | |||
| 740 | This is free software, licensed under: | ||
| 741 | |||
| 742 | The GNU General Public License, Version 3, June 2007 | ||
| 743 | |||
| 744 | |||
| 745 | =cut | ||
| 746 | |||
| 747 | 28 | 1; | |
| 748 | |||