@metta-ts/libraries 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1265 @@
1
+ // src/index.ts
2
+ import { registerBuiltinModule } from "@metta-ts/core";
3
+
4
+ // src/generated/sources.ts
5
+ var LIBRARY_MODULE_SRCS = {
6
+ vector: '\n (: dot (-> Expression Expression Number))\n (: norm (-> Expression Number))\n (: cosine (-> Expression Expression Number))\n (: cosine-of-normalized (-> Expression Expression Number))\n (: random-normal-vector (-> Number Expression))\n\n (@doc dot\n (@desc "Dot product of two equal-length numeric vectors written as expression lists")\n (@params ((@param "First vector") (@param "Second vector")))\n (@return "Sum of the elementwise products"))\n (= (dot $u $v)\n (if (== $u ())\n 0.0\n (let* ((($a $as) (decons-atom $u)) (($b $bs) (decons-atom $v)))\n (+ (* $a $b) (dot $as $bs)))))\n\n (@doc norm\n (@desc "Euclidean norm (length) of a numeric vector")\n (@params ((@param "Vector")))\n (@return "Square root of the vector dotted with itself"))\n (= (norm $v) (sqrt-math (dot $v $v)))\n\n (@doc cosine-of-normalized\n (@desc "Cosine similarity when both vectors are already unit length, which is just their dot product")\n (@params ((@param "First unit vector") (@param "Second unit vector")))\n (@return "Dot product of the two vectors"))\n (= (cosine-of-normalized $a $b) (dot $a $b))\n\n (@doc cosine\n (@desc "Cosine similarity of two numeric vectors, their dot product over the product of their norms")\n (@params ((@param "First vector") (@param "Second vector")))\n (@return "Dot product divided by the product of the norms"))\n (= (cosine $a $b)\n (/ (dot $a $b) (* (norm $a) (norm $b))))\n\n (@doc random-normal-vector\n (@desc "A random N-dimensional unit vector: N samples in [0, 1) scaled to length one")\n (@params ((@param "Dimension N")))\n (@return "A normalized vector of length N"))\n (= (random-normal-vector $n) (random-normal-vector-acc $n ()))\n ; cons-atom is a data constructor and does not evaluate its head, so force each random draw with\n ; a let before consing; otherwise the unevaluated (random-float ...) is re-rolled by norm and map.\n (= (random-normal-vector-acc $n $acc)\n (if (> $n 0)\n (let $r (random-float 0.0 1.0)\n (random-normal-vector-acc (- $n 1) (cons-atom $r $acc)))\n (let $len (norm $acc) (map-atom $acc $x (/ $x $len)))))\n',
7
+ roman: '\n ; ---------- Tracing ----------\n (: traceid (-> $t $t))\n (@doc traceid\n (@desc "Print an atom to the trace log and return it unchanged, for inspecting a value mid-evaluation")\n (@params ((@param "The atom to trace and return")))\n (@return "The same atom"))\n (= (traceid $x) (trace! $x $x))\n\n (: tracem (-> Atom $t $t))\n (@doc tracem\n (@desc "Print a labelled atom (the message paired with the value) to the trace log and return the value unchanged")\n (@params ((@param "A label printed alongside the value") (@param "The value to trace and return")))\n (@return "The value, unchanged"))\n (= (tracem $msg $x) (trace! ($msg $x) $x))\n\n ; ---------- Higher-order functions over expression lists ----------\n (: map-flat (-> Atom Expression Expression))\n (@doc map-flat\n (@desc "Apply a unary function to each element of a flat expression list, returning the list of results")\n (@params ((@param "A unary function f, applied as (f element)") (@param "An expression list")))\n (@return "The list of (f element) values, in order"))\n (= (map-flat $f $l)\n (if (== $l ())\n ()\n (let* ((($x $xs) (decons-atom $l))\n ($h ($f $x))\n ($t (map-flat $f $xs)))\n (cons-atom $h $t))))\n\n (: map-nested (-> Atom Expression Expression))\n (@doc map-nested\n (@desc "Apply a unary function to each leaf of a nested expression list, recursing into sub-expressions and keeping the shape")\n (@params ((@param "A unary function f, applied as (f leaf)") (@param "A possibly nested expression list")))\n (@return "The list with f applied at every leaf and the nesting preserved"))\n (= (map-nested $f $l)\n (if (== $l ())\n ()\n (let* ((($x $xs) (decons-atom $l)))\n (if (is-expr $x)\n (let* (($h (map-nested $f $x)) ($t (map-nested $f $xs))) (cons-atom $h $t))\n (let* (($h ($f $x)) ($t (map-nested $f $xs))) (cons-atom $h $t))))))\n\n (: fold-flat (-> Atom $a Expression $a))\n (@doc fold-flat\n (@desc "Left fold over a flat expression list, combining the accumulator with each element left to right as (f acc element)")\n (@params ((@param "A binary function f, applied as (f acc element)") (@param "The initial accumulator") (@param "An expression list")))\n (@return "The final accumulator"))\n (= (fold-flat $f $init $l)\n (if (== $l ())\n $init\n (let* ((($x $xs) (decons-atom $l)))\n (fold-flat $f ($f $init $x) $xs))))\n\n (: foldr-flat (-> Atom $a Expression $a))\n (@doc foldr-flat\n (@desc "Right fold over a flat expression list, combining each element with the folded tail as (f element acc)")\n (@params ((@param "A binary function f, applied as (f element acc)") (@param "The initial accumulator") (@param "An expression list")))\n (@return "The folded result"))\n (= (foldr-flat $f $init $l)\n (if (== $l ())\n $init\n (let* ((($x $xs) (decons-atom $l)))\n ($f $x (foldr-flat $f $init $xs)))))\n\n (: fold-nested (-> Atom $a Expression $a))\n (@doc fold-nested\n (@desc "Left fold over a nested expression list, folding recursively through each sub-expression before continuing")\n (@params ((@param "A binary function f, applied as (f acc leaf)") (@param "The initial accumulator") (@param "A possibly nested expression list")))\n (@return "The final accumulator after folding every leaf"))\n (= (fold-nested $f $init $l)\n (if (== $l ())\n $init\n (let* ((($x $xs) (decons-atom $l)))\n (if (is-expr $x)\n (fold-nested $f (fold-nested $f $init $x) $xs)\n (fold-nested $f ($f $init $x) $xs)))))\n\n ; ---------- Set operations on expression lists ----------\n ; A predicate is any two-argument function returning a Bool. The = variants match by unification, the\n ; == variants by strict equality, and the =a variants by alpha-equality.\n\n ; True when $a matches some element of $bs under the two-argument predicate $pred.\n (= (roman-elem? $pred $a $bs)\n (if (== $bs ())\n False\n (let* ((($b $rest) (decons-atom $bs)))\n (if ($pred $a $b) True (roman-elem? $pred $a $rest)))))\n\n ; The = predicate, re-expressed for a Hyperon engine: two atoms are related when they unify.\n (= (roman-unify? $a $b) (unify $a $b True False))\n\n (: /?\\ (-> Atom Expression Expression Expression))\n (@doc /?\\\n (@desc "Intersection of two expression lists under a predicate: the elements of the first list that match some element of the second")\n (@params ((@param "A two-argument boolean predicate") (@param "The first expression list") (@param "The second expression list")))\n (@return "The elements of the first list that match under the predicate, in their original order"))\n (= (/?\\ $pred $l $bs)\n (if (== $l ())\n ()\n (let* ((($a $as) (decons-atom $l)))\n (if (roman-elem? $pred $a $bs)\n (let $rest (/?\\ $pred $as $bs) (cons-atom $a $rest))\n (/?\\ $pred $as $bs)))))\n\n (: /=\\ (-> Expression Expression Expression))\n (@doc /=\\\n (@desc "Intersection by unification")\n (@params ((@param "First list") (@param "Second list")))\n (@return "Elements of the first list that unify with some element of the second"))\n (= (/=\\ $a $b) (/?\\ roman-unify? $a $b))\n\n (: /==\\ (-> Expression Expression Expression))\n (@doc /==\\\n (@desc "Intersection by strict equality")\n (@params ((@param "First list") (@param "Second list")))\n (@return "Elements of the first list equal to some element of the second"))\n (= (/==\\ $a $b) (/?\\ == $a $b))\n\n (: /=a\\ (-> Expression Expression Expression))\n (@doc /=a\\\n (@desc "Intersection by alpha-equality")\n (@params ((@param "First list") (@param "Second list")))\n (@return "Elements of the first list alpha-equal to some element of the second"))\n (= (/=a\\ $a $b) (/?\\ =alpha $a $b))\n\n (: \\? (-> Atom Expression Expression Expression))\n (@doc \\?\n (@desc "Subtraction of two expression lists under a predicate: the elements of the first list that match no element of the second")\n (@params ((@param "A two-argument boolean predicate") (@param "The first expression list") (@param "The second expression list")))\n (@return "The elements of the first list with no match in the second, in their original order"))\n (= (\\? $pred $l $bs)\n (if (== $l ())\n ()\n (let* ((($a $as) (decons-atom $l)))\n (if (roman-elem? $pred $a $bs)\n (\\? $pred $as $bs)\n (let $rest (\\? $pred $as $bs) (cons-atom $a $rest))))))\n\n (: \\= (-> Expression Expression Expression))\n (@doc \\=\n (@desc "Subtraction by unification")\n (@params ((@param "First list") (@param "Second list")))\n (@return "Elements of the first list that unify with no element of the second"))\n (= (\\= $a $b) (\\? roman-unify? $a $b))\n\n (: \\== (-> Expression Expression Expression))\n (@doc \\==\n (@desc "Subtraction by strict equality")\n (@params ((@param "First list") (@param "Second list")))\n (@return "Elements of the first list equal to no element of the second"))\n (= (\\== $a $b) (\\? == $a $b))\n\n (: \\=a (-> Expression Expression Expression))\n (@doc \\=a\n (@desc "Subtraction by alpha-equality")\n (@params ((@param "First list") (@param "Second list")))\n (@return "Elements of the first list alpha-equal to no element of the second"))\n (= (\\=a $a $b) (\\? =alpha $a $b))\n\n (: \\?/ (-> Atom Expression Expression Expression))\n (@doc \\?/\n (@desc "Union of two expression lists under a predicate: the second list, prefixed by the elements of the first that it does not already contain")\n (@params ((@param "A two-argument boolean predicate") (@param "The first expression list") (@param "The second expression list")))\n (@return "The unmatched elements of the first list followed by the whole second list"))\n (= (\\?/ $pred $l $bs)\n (if (== $l ())\n $bs\n (let* ((($a $as) (decons-atom $l)))\n (if (roman-elem? $pred $a $bs)\n (\\?/ $pred $as $bs)\n (let $rest (\\?/ $pred $as $bs) (cons-atom $a $rest))))))\n\n (: \\=/ (-> Expression Expression Expression))\n (@doc \\=/\n (@desc "Union by unification")\n (@params ((@param "First list") (@param "Second list")))\n (@return "The second list prefixed by the elements of the first that unify with none of it"))\n (= (\\=/ $a $b) (\\?/ roman-unify? $a $b))\n\n (: \\==/ (-> Expression Expression Expression))\n (@doc \\==/\n (@desc "Union by strict equality")\n (@params ((@param "First list") (@param "Second list")))\n (@return "The second list prefixed by the elements of the first equal to none of it"))\n (= (\\==/ $a $b) (\\?/ == $a $b))\n\n (: \\=a/ (-> Expression Expression Expression))\n (@doc \\=a/\n (@desc "Union by alpha-equality")\n (@params ((@param "First list") (@param "Second list")))\n (@return "The second list prefixed by the elements of the first alpha-equal to none of it"))\n (= (\\=a/ $a $b) (\\?/ =alpha $a $b))\n\n ; ---------- Function composition ----------\n (: . (-> Atom Atom Atom $t))\n (@doc .\n (@desc "Compose two unary functions and apply them to an argument, computing (f1 (f2 arg))")\n (@params ((@param "The outer function f1") (@param "The inner function f2") (@param "The argument")))\n (@return "(f1 (f2 arg))"))\n (= (. $f1 $f2 $arg) ($f1 ($f2 $arg)))\n\n (: .. (-> Atom Atom Atom $t))\n (@doc ..\n (@desc "Compose two unary functions and apply them to an argument, computing (f1 (f2 arg)) (an alias of .)")\n (@params ((@param "The outer function f1") (@param "The inner function f2") (@param "The argument")))\n (@return "(f1 (f2 arg))"))\n (= (.. $f1 $f2 $arg) ($f1 ($f2 $arg)))\n\n (: .: (-> Atom Atom Atom Atom $t))\n (@doc .:\n (@desc "Compose a unary function with a binary function, computing (f1 (f2 arg1 arg2))")\n (@params ((@param "The outer unary function f1") (@param "The inner binary function f2") (@param "First argument") (@param "Second argument")))\n (@return "(f1 (f2 arg1 arg2))"))\n (= (.: $f1 $f2 $arg1 $arg2) ($f1 ($f2 $arg1 $arg2)))\n\n (: &&& (-> Atom Atom Atom Expression))\n (@doc &&&\n (@desc "Fan out one argument through two functions, pairing their results as ((f1 arg) (f2 arg))")\n (@params ((@param "First function f1") (@param "Second function f2") (@param "The shared argument")))\n (@return "The two-element list ((f1 arg) (f2 arg))"))\n (= (&&& $f1 $f2 $arg) (($f1 $arg) ($f2 $arg)))\n\n (: &^& (-> Atom Atom Atom $t))\n (@doc &^&\n (@desc "Fan out one argument through two functions and return both results non-deterministically")\n (@params ((@param "First function f1") (@param "Second function f2") (@param "The shared argument")))\n (@return "(f1 arg), then (f2 arg), as separate results"))\n (= (&^& $f1 $f2 $arg) (superpose (($f1 $arg) ($f2 $arg))))\n\n ; ---------- Reverse function matching ----------\n (: @ (-> Atom Atom $t))\n (@doc @\n (@desc "Match a pattern against a value and return the pattern with its variables bound, running the usual match in reverse")\n (@params ((@param "A pattern atom") (@param "A value to match the pattern against")))\n (@return "The pattern instantiated by matching it against the value"))\n (= (@ $a $b) (let $a $b $a))\n\n ; ---------- List ends ----------\n (: head (-> Expression $t))\n (@doc head\n (@desc "The first element of an expression list")\n (@params ((@param "A non-empty expression list")))\n (@return "The first element"))\n (= (head $l) (car-atom $l))\n\n (: tail (-> Expression Expression))\n (@doc tail\n (@desc "Every element of an expression list except the first")\n (@params ((@param "A non-empty expression list")))\n (@return "The list without its first element"))\n (= (tail $l) (cdr-atom $l))\n\n (: mylast (-> Expression $t))\n (@doc mylast\n (@desc "The last element of an expression list, found as the first element of its reverse")\n (@params ((@param "A non-empty expression list")))\n (@return "The last element"))\n (= (mylast $l) (let $r (reverse $l) (car-atom $r)))\n\n (: init (-> Expression Expression))\n (@doc init\n (@desc "Every element of an expression list except the last, found by reversing, dropping the head, and reversing back")\n (@params ((@param "A non-empty expression list")))\n (@return "The list without its last element"))\n (= (init $l) (let* (($r (reverse $l)) ($c (cdr-atom $r))) (reverse $c)))\n\n (: rcons (-> Expression Atom Expression))\n (@doc rcons\n (@desc "Append a single element to the end of an expression list")\n (@params ((@param "An expression list") (@param "The element to append")))\n (@return "The list with the element added at the end"))\n (= (rcons $xs $x) (union-atom $xs ($x)))\n\n ; ---------- Pair accessors ----------\n (: fst (-> Expression $t))\n (@doc fst\n (@desc "The first component of a two-element expression")\n (@params ((@param "A two-element expression (a b)")))\n (@return "The first component a"))\n (= (fst ($a $b)) $a)\n\n (: snd (-> Expression $t))\n (@doc snd\n (@desc "The second component of a two-element expression")\n (@params ((@param "A two-element expression (a b)")))\n (@return "The second component b"))\n (= (snd ($a $b)) $b)\n',
8
+ combinatorics: '\n (: range (-> Number Number Number))\n (: choose2 (-> Expression Expression))\n (: choose2l (-> Expression Expression))\n (: chooseKl (-> Expression Number Expression))\n (: chooseK (-> Expression Number Expression))\n (: takeK (-> Number Expression Expression))\n\n (@doc range\n (@desc "Each integer from K up to but not including N, delivered as separate nondeterministic results")\n (@params ((@param "Start value K, included") (@param "End value N, excluded")))\n (@return "One result per integer in the half-open range from K to N"))\n (= (range $K $N) (let $lst (range-list $K $N) (superpose $lst)))\n (= (range-list $K $N)\n (if (< $K $N)\n (let $rest (range-list (+ $K 1) $N) (cons-atom $K $rest))\n ()))\n\n (@doc choose2\n (@desc "Each unordered pair of distinct positions in a list, so (a b) appears but (b a) does not")\n (@params ((@param "List to draw the pair from")))\n (@return "One (first second) pair per combination, nondeterministically"))\n (= (choose2 $L)\n (let $j (range 0 (length $L))\n (let $i (range 0 $j)\n ((index-atom $L $i) (index-atom $L $j)))))\n\n (@doc choose2l\n (@desc "Every unordered pair of distinct list elements, gathered into one tuple")\n (@params ((@param "List to draw pairs from")))\n (@return "A tuple holding all the pairs"))\n (= (choose2l $L) (collapse (choose2 $L)))\n\n (@doc chooseKl\n (@desc "All the ways to pick exactly K elements from a list, unordered, as a list of those combinations")\n (@params ((@param "List to choose from") (@param "Number of elements K to pick")))\n (@return "A list whose elements are the K-element combinations"))\n (= (chooseKl $L $k)\n (if (== $k 0)\n (())\n (if (== $L ())\n ()\n (let* ((($h $t) (decons-atom $L)))\n (let $sub (chooseKl $t (- $k 1))\n (append (map-atom $sub $c (cons-atom $h $c))\n (chooseKl $t $k)))))))\n\n (@doc chooseK\n (@desc "Pick exactly K elements from a list, unordered, one combination per nondeterministic result")\n (@params ((@param "List to choose from") (@param "Number of elements K to pick")))\n (@return "One K-element combination per result"))\n (= (chooseK $L $k) (let $options (chooseKl $L $k) (superpose $options)))\n\n (@doc takeK\n (@desc "The first K elements of a list, or the whole list when it has fewer than K")\n (@params ((@param "Count K of leading elements to keep") (@param "List to take from")))\n (@return "A list of at most the first K elements"))\n (= (takeK $k $L)\n (if (== $L ())\n ()\n (if (> $k 0)\n (let* ((($head $tail) (decons-atom $L)))\n (let $rest (takeK (- $k 1) $tail) (cons-atom $head $rest)))\n ())))\n',
9
+ patrick: '\n (: compose (-> Expression Atom %Undefined%))\n\n (@doc compose\n (@desc "Compose a list of single-argument functions, applied right to left, over an argument tuple")\n (@params ((@param "List of function symbols, innermost last") (@param "Argument tuple passed to the innermost function")))\n (@return "The result of the composed application"))\n (= (compose $fs $args)\n (let* ((($f $rest) (decons-atom $fs)))\n (if (== $rest ())\n (if (== (length $args) 1)\n (let ($arg) $args ($f $arg))\n (let $func (cons-atom $f $args) (reduce $func)))\n ($f (compose $rest $args)))))\n',
10
+ datastructures: `
11
+ (: empty-queue (-> Expression))
12
+ (: enqueue (-> Atom Expression Expression))
13
+ (: dequeue (-> Expression Expression))
14
+ (: add-unique-or-fail (-> Grounded Atom %Undefined%))
15
+
16
+ (@doc empty-queue
17
+ (@desc "The empty queue: two empty stacks and a zero count")
18
+ (@params ())
19
+ (@return "A queue (queue () () 0) holding no elements"))
20
+ (= (empty-queue) (queue () () 0))
21
+
22
+ (@doc enqueue
23
+ (@desc "Add an element to the back of the queue in amortized O(1) by pushing it onto the in-stack")
24
+ (@params ((@param "Element to add") (@param "Queue")))
25
+ (@return "The queue with the element appended at the back"))
26
+ (= (enqueue $e $q)
27
+ (let (queue $in $out $n) $q
28
+ (queue (cons-atom $e $in) $out (+ $n 1))))
29
+
30
+ (@doc dequeue
31
+ (@desc "Remove the front element and return it paired with the rest of the queue. When the out-stack is empty it first reverses the in-stack onto the out-stack, the amortized step. Yields nothing on an empty queue")
32
+ (@params ((@param "Queue")))
33
+ (@return "(Pair <front element> <rest of the queue>), or no result when the queue is empty"))
34
+ (= (dequeue $q)
35
+ (let (queue $in $out $n) $q
36
+ (if (== $out ())
37
+ (if (== $in ())
38
+ (empty)
39
+ (let* (($rev (reverse $in)) (($h $t) (decons-atom $rev)))
40
+ (Pair $h (queue () $t (- $n 1)))))
41
+ (let* ((($h $t) (decons-atom $out)))
42
+ (Pair $h (queue $in $t (- $n 1)))))))
43
+
44
+ (@doc add-unique-or-fail
45
+ (@desc "Intern (s <repr of the expression>) into the space only if no equal key is already present, otherwise yield nothing. A fast set insertion keyed on the atom's textual form")
46
+ (@params ((@param "Space") (@param "Expression to intern as a key")))
47
+ (@return "The add-atom result when newly inserted, or no result when the key already exists"))
48
+ (= (add-unique-or-fail $space $expression)
49
+ (let $st (s (repr $expression))
50
+ (if (== (,) (collapse (once (match $space $st True))))
51
+ (add-atom $space $st)
52
+ (empty))))
53
+ `,
54
+ spaces: '\n (: migrateAtoms (-> Grounded Grounded Atom %Undefined%))\n (: remove-all-atoms (-> Grounded %Undefined%))\n\n (@doc migrateAtoms\n (@desc "Move every atom matching the pattern from one space to another: add each match to the target space, then remove it from the source space")\n (@params ((@param "Source space") (@param "Target space") (@param "Pattern to match and move")))\n (@return "The per-atom results of the move"))\n (= (migrateAtoms $FromSpace $ToSpace $Pattern)\n (match $FromSpace $Pattern\n (let $moved (add-atom $ToSpace $Pattern)\n (remove-atom $FromSpace $Pattern))))\n\n (@doc remove-all-atoms\n (@desc "Remove every atom from the space by matching each one and removing it")\n (@params ((@param "Space")))\n (@return "The collapsed results of removing each atom"))\n (= (remove-all-atoms $space)\n (collapse (match $space $x (remove-atom $space $x))))\n',
55
+ nars: `
56
+ ; ---------- Truth values ----------
57
+ (: Truth_c2w (-> Number Number))
58
+ (@doc Truth_c2w
59
+ (@desc "Convert NARS confidence to evidence weight")
60
+ (@params ((@param "Confidence c")))
61
+ (@return "Evidence weight c / (1 - c)"))
62
+ (= (Truth_c2w $c)
63
+ (/ $c (- 1 $c)))
64
+
65
+ (: Truth_w2c (-> Number Number))
66
+ (@doc Truth_w2c
67
+ (@desc "Convert evidence weight to NARS confidence")
68
+ (@params ((@param "Evidence weight w")))
69
+ (@return "Confidence w / (w + 1)"))
70
+ (= (Truth_w2c $w)
71
+ (/ $w (+ $w 1)))
72
+
73
+ (: Truth_Deduction (-> Expression Expression Expression))
74
+ (@doc Truth_Deduction
75
+ (@desc "NAL deduction truth function over two simple truth values")
76
+ (@params ((@param "First truth value (stv f c)") (@param "Second truth value (stv f c)")))
77
+ (@return "(stv (* f1 f2) (* f1 f2 c1 c2))"))
78
+ (= (Truth_Deduction (stv $f1 $c1)
79
+ (stv $f2 $c2))
80
+ (stv (* $f1 $f2) (* (* $f1 $f2) (* $c1 $c2))))
81
+
82
+ (: Truth_Abduction (-> Expression Expression Expression))
83
+ (@doc Truth_Abduction
84
+ (@desc "NAL abduction truth function")
85
+ (@params ((@param "First truth value (stv f c)") (@param "Second truth value (stv f c)")))
86
+ (@return "Abductive simple truth value"))
87
+ (= (Truth_Abduction (stv $f1 $c1)
88
+ (stv $f2 $c2))
89
+ (stv $f2 (Truth_w2c (* (* $f1 $c1) $c2))))
90
+
91
+ (: Truth_Induction (-> Expression Expression Expression))
92
+ (@doc Truth_Induction
93
+ (@desc "NAL induction, defined as reversed abduction")
94
+ (@params ((@param "First truth value") (@param "Second truth value")))
95
+ (@return "Inductive simple truth value"))
96
+ (= (Truth_Induction $T1 $T2)
97
+ (Truth_Abduction $T2 $T1))
98
+
99
+ (: Truth_Exemplification (-> Expression Expression Expression))
100
+ (@doc Truth_Exemplification
101
+ (@desc "NAL exemplification truth function")
102
+ (@params ((@param "First truth value (stv f c)") (@param "Second truth value (stv f c)")))
103
+ (@return "Exemplification simple truth value"))
104
+ (= (Truth_Exemplification (stv $f1 $c1)
105
+ (stv $f2 $c2))
106
+ (stv 1.0 (Truth_w2c (* (* $f1 $f2) (* $c1 $c2)))))
107
+
108
+ (: Truth_StructuralDeduction (-> Expression Expression))
109
+ (@doc Truth_StructuralDeduction
110
+ (@desc "Structural deduction against the fixed NARS truth value (stv 1.0 0.9)")
111
+ (@params ((@param "Input truth value")))
112
+ (@return "Structurally deduced truth value"))
113
+ (= (Truth_StructuralDeduction $T)
114
+ (Truth_Deduction $T (stv 1.0 0.9)))
115
+
116
+ (: Truth_Negation (-> Expression Expression))
117
+ (@doc Truth_Negation
118
+ (@desc "Negate the frequency of a simple truth value while preserving confidence")
119
+ (@params ((@param "Truth value (stv f c)")))
120
+ (@return "(stv (1 - f) c)"))
121
+ (= (Truth_Negation (stv $f $c))
122
+ (stv (- 1 $f) $c))
123
+
124
+ (: Truth_StructuralDeductionNegated (-> Expression Expression))
125
+ (@doc Truth_StructuralDeductionNegated
126
+ (@desc "Structural deduction followed by truth negation")
127
+ (@params ((@param "Input truth value")))
128
+ (@return "Negated structural deduction truth value"))
129
+ (= (Truth_StructuralDeductionNegated $T)
130
+ (Truth_Negation (Truth_StructuralDeduction $T)))
131
+
132
+ (: Truth_Intersection (-> Expression Expression Expression))
133
+ (@doc Truth_Intersection
134
+ (@desc "Truth function for intersection")
135
+ (@params ((@param "First truth value (stv f c)") (@param "Second truth value (stv f c)")))
136
+ (@return "(stv (* f1 f2) (* c1 c2))"))
137
+ (= (Truth_Intersection (stv $f1 $c1)
138
+ (stv $f2 $c2))
139
+ (stv (* $f1 $f2) (* $c1 $c2)))
140
+
141
+ (: Truth_StructuralIntersection (-> Expression Expression))
142
+ (@doc Truth_StructuralIntersection
143
+ (@desc "Structural intersection against the fixed NARS truth value (stv 1.0 0.9)")
144
+ (@params ((@param "Input truth value")))
145
+ (@return "Structurally intersected truth value"))
146
+ (= (Truth_StructuralIntersection $T)
147
+ (Truth_Intersection $T (stv 1.0 0.9)))
148
+
149
+ (: Truth_or (-> Number Number Number))
150
+ (@doc Truth_or
151
+ (@desc "Probabilistic OR over two frequencies")
152
+ (@params ((@param "First frequency") (@param "Second frequency")))
153
+ (@return "1 - (1 - a) * (1 - b)"))
154
+ (= (Truth_or $a $b)
155
+ (- 1 (* (- 1 $a) (- 1 $b))))
156
+
157
+ (: Truth_Comparison (-> Expression Expression Expression))
158
+ (@doc Truth_Comparison
159
+ (@desc "NAL comparison truth function")
160
+ (@params ((@param "First truth value (stv f c)") (@param "Second truth value (stv f c)")))
161
+ (@return "Comparison simple truth value"))
162
+ (= (Truth_Comparison (stv $f1 $c1)
163
+ (stv $f2 $c2))
164
+ (let $f0 (Truth_or $f1 $f2)
165
+ (stv (if (== $f0 0.0)
166
+ 0.0
167
+ (/ (* $f1 $f2) $f0))
168
+ (Truth_w2c (* $f0 (* $c1 $c2))))))
169
+
170
+ (: Truth_Analogy (-> Expression Expression Expression))
171
+ (@doc Truth_Analogy
172
+ (@desc "NAL analogy truth function")
173
+ (@params ((@param "First truth value (stv f c)") (@param "Second truth value (stv f c)")))
174
+ (@return "Analogy simple truth value"))
175
+ (= (Truth_Analogy (stv $f1 $c1)
176
+ (stv $f2 $c2))
177
+ (stv (* $f1 $f2) (* (* $c1 $c2) $f2)))
178
+
179
+ (: Truth_Resemblance (-> Expression Expression Expression))
180
+ (@doc Truth_Resemblance
181
+ (@desc "NAL resemblance truth function")
182
+ (@params ((@param "First truth value (stv f c)") (@param "Second truth value (stv f c)")))
183
+ (@return "Resemblance simple truth value"))
184
+ (= (Truth_Resemblance (stv $f1 $c1)
185
+ (stv $f2 $c2))
186
+ (stv (* $f1 $f2) (* (* $c1 $c2) (Truth_or $f1 $f2))))
187
+
188
+ (: Truth_Union (-> Expression Expression Expression))
189
+ (@doc Truth_Union
190
+ (@desc "PeTTa lib_nars union truth function; the upstream body returns a two-element expression, not an stv-headed value")
191
+ (@params ((@param "First truth value (stv f c)") (@param "Second truth value (stv f c)")))
192
+ (@return "A two-element expression matching PeTTa's source"))
193
+ (= (Truth_Union (stv $f1 $c1)
194
+ (stv $f2 $c2))
195
+ ((Truth_or $f1 $f2) (* $c1 $c2)))
196
+
197
+ (: Truth_Difference (-> Expression Expression Expression))
198
+ (@doc Truth_Difference
199
+ (@desc "NAL difference truth function")
200
+ (@params ((@param "First truth value (stv f c)") (@param "Second truth value (stv f c)")))
201
+ (@return "Difference simple truth value"))
202
+ (= (Truth_Difference (stv $f1 $c1)
203
+ (stv $f2 $c2))
204
+ (stv (* $f1 (- 1 $f2)) (* $c1 $c2)))
205
+
206
+ (: Truth_DecomposePNN (-> Expression Expression Expression))
207
+ (@doc Truth_DecomposePNN
208
+ (@desc "NAL decomposition truth function for positive-negative-negative decomposition")
209
+ (@params ((@param "First truth value (stv f c)") (@param "Second truth value (stv f c)")))
210
+ (@return "Decomposition simple truth value"))
211
+ (= (Truth_DecomposePNN (stv $f1 $c1)
212
+ (stv $f2 $c2))
213
+ (let $fn (* $f1 (- 1 $f2))
214
+ (stv (- 1 $fn) (* $fn (* $c1 $c2)))))
215
+
216
+ (: Truth_DecomposeNPP (-> Expression Expression Expression))
217
+ (@doc Truth_DecomposeNPP
218
+ (@desc "NAL decomposition truth function for negative-positive-positive decomposition")
219
+ (@params ((@param "First truth value (stv f c)") (@param "Second truth value (stv f c)")))
220
+ (@return "Decomposition simple truth value"))
221
+ (= (Truth_DecomposeNPP (stv $f1 $c1)
222
+ (stv $f2 $c2))
223
+ (let $f (* (- 1 $f1) $f2)
224
+ (stv $f (* $f (* $c1 $c2)))))
225
+
226
+ (: Truth_DecomposePNP (-> Expression Expression Expression))
227
+ (@doc Truth_DecomposePNP
228
+ (@desc "NAL decomposition truth function for positive-negative-positive decomposition")
229
+ (@params ((@param "First truth value (stv f c)") (@param "Second truth value (stv f c)")))
230
+ (@return "Decomposition simple truth value"))
231
+ (= (Truth_DecomposePNP (stv $f1 $c1)
232
+ (stv $f2 $c2))
233
+ (let $f (* $f1 (- 1 $f2))
234
+ (stv $f (* $f (* $c1 $c2)))))
235
+
236
+ (: Truth_DecomposePPP (-> Expression Expression Expression))
237
+ (@doc Truth_DecomposePPP
238
+ (@desc "NAL decomposition truth function for positive-positive-positive decomposition")
239
+ (@params ((@param "First truth value") (@param "Second truth value")))
240
+ (@return "Decomposition simple truth value"))
241
+ (= (Truth_DecomposePPP $v1 $v2)
242
+ (Truth_DecomposeNPP (Truth_Negation $v1) $v2))
243
+
244
+ (: Truth_DecomposeNNN (-> Expression Expression Expression))
245
+ (@doc Truth_DecomposeNNN
246
+ (@desc "PeTTa lib_nars decomposition for negative-negative-negative; the upstream body returns a two-element expression, not an stv-headed value")
247
+ (@params ((@param "First truth value (stv f c)") (@param "Second truth value (stv f c)")))
248
+ (@return "A two-element expression matching PeTTa's source"))
249
+ (= (Truth_DecomposeNNN (stv $f1 $c1)
250
+ (stv $f2 $c2))
251
+ (let $fn (* (- 1 $f1) (- 1 $f2))
252
+ ((- 1 $fn) (* $fn (* $c1 $c2)))))
253
+
254
+ (: Truth_Eternalize (-> Expression Expression))
255
+ (@doc Truth_Eternalize
256
+ (@desc "Eternalize a simple truth value by converting its confidence as a weight")
257
+ (@params ((@param "Truth value (stv f c)")))
258
+ (@return "Eternalized simple truth value"))
259
+ (= (Truth_Eternalize (stv $f $c))
260
+ (stv $f (Truth_w2c $c)))
261
+
262
+ (: Truth_Revision (-> Expression Expression Expression))
263
+ (@doc Truth_Revision
264
+ (@desc "Revise two independent simple truth values by combining their evidence weights")
265
+ (@params ((@param "First truth value (stv f c)") (@param "Second truth value (stv f c)")))
266
+ (@return "Revised simple truth value"))
267
+ (= (Truth_Revision (stv $f1 $c1)
268
+ (stv $f2 $c2))
269
+ (let* (($w1 (Truth_c2w $c1))
270
+ ($w2 (Truth_c2w $c2))
271
+ ($w (+ $w1 $w2))
272
+ ($f (/ (+ (* $w1 $f1) (* $w2 $f2)) $w))
273
+ ($c (Truth_w2c $w)))
274
+ (stv (min 1.00 $f) (min 0.99 (max (max $c $c1) $c2)))))
275
+
276
+ (: Truth_Expectation (-> Expression Number))
277
+ (@doc Truth_Expectation
278
+ (@desc "Expectation of a simple truth value")
279
+ (@params ((@param "Truth value (stv f c)")))
280
+ (@return "c * (f - 0.5) + 0.5"))
281
+ (= (Truth_Expectation (stv $f $c))
282
+ (+ (* $c (- $f 0.5)) 0.5))
283
+
284
+ ; ---------- Inference rules ----------
285
+ (@doc |-
286
+ (@desc "PeTTa lib_nars NAL inference rules. Binary forms combine two judgements; unary forms decompose one judgement")
287
+ (@params ((@param "One or two NARS judgements, each written as (<term> <truth>)")))
288
+ (@return "A derived judgement (<term> <truth>)"))
289
+
290
+ ; NAL-1: revision and inheritance syllogisms.
291
+ (= (|- ($T $T1) ($T $T2)) ($T (Truth_Revision $T1 $T2)))
292
+ (= (|- ((--> $a $b) $T1) ((--> $b $c) $T2)) ((--> $a $c) (Truth_Deduction $T1 $T2)))
293
+ (= (|- ((--> $a $b) $T1) ((--> $a $c) $T2)) ((--> $c $b) (Truth_Induction $T1 $T2)))
294
+ (= (|- ((--> $a $c) $T1) ((--> $b $c) $T2)) ((--> $b $a) (Truth_Abduction $T1 $T2)))
295
+ (= (|- ((--> $a $b) $T1) ((--> $b $c) $T2)) ((--> $c $a) (Truth_Exemplification $T1 $T2)))
296
+
297
+ ; PeTTa's lib_nars source has no NAL-2 block.
298
+
299
+ ; NAL-3: sets and extensional/intensional decomposition.
300
+ (= (|- ((--> ({} $A $B) $M) $T)) ((--> ({} $A) $M) (Truth_StructuralDeduction $T)))
301
+ (= (|- ((--> ({} $A $B) $M) $T)) ((--> ({} $B) $M) (Truth_StructuralDeduction $T)))
302
+ (= (|- ((--> $M ([] $A $B)) $T)) ((--> $M ([] $A)) (Truth_StructuralDeduction $T)))
303
+ (= (|- ((--> $M ([] $A $B)) $T)) ((--> $M ([] $B)) (Truth_StructuralDeduction $T)))
304
+ (= (|- ((--> (\u222A $S $P) $M) $T)) ((--> $S $M) (Truth_StructuralDeduction $T)))
305
+ (= (|- ((--> $M (\u2229 $S $P)) $T)) ((--> $M $S) (Truth_StructuralDeduction $T)))
306
+ (= (|- ((--> (\u222A $S $P) $M) $T)) ((--> $P $M) (Truth_StructuralDeduction $T)))
307
+ (= (|- ((--> $M (\u2229 $S $P)) $T)) ((--> $M $P) (Truth_StructuralDeduction $T)))
308
+ (= (|- ((--> (~ $A $S) $M) $T)) ((--> $A $M) (Truth_StructuralDeduction $T)))
309
+ (= (|- ((--> $M (\u2212 $B $S)) $T)) ((--> $M $B) (Truth_StructuralDeduction $T)))
310
+ (= (|- ((--> (~ $A $S) $M) $T)) ((--> $S $M) (Truth_StructuralDeductionNegated $T)))
311
+ (= (|- ((--> $M (\u2212 $B $S)) $T)) ((--> $M $S) (Truth_StructuralDeductionNegated $T)))
312
+ (= (|- ((--> $S $M) $T1) ((--> (\u222A $S $P) $M) $T2)) ((--> $P $M) (Truth_DecomposePNN $T1 $T2)))
313
+ (= (|- ((--> $P $M) $T1) ((--> (\u222A $S $P) $M) $T2)) ((--> $S $M) (Truth_DecomposePNN $T1 $T2)))
314
+ (= (|- ((--> $S $M) $T1) ((--> (\u2229 $S $P) $M) $T2)) ((--> $P $M) (Truth_DecomposeNPP $T1 $T2)))
315
+ (= (|- ((--> $P $M) $T1) ((--> (\u2229 $S $P) $M) $T2)) ((--> $S $M) (Truth_DecomposeNPP $T1 $T2)))
316
+ (= (|- ((--> $S $M) $T1) ((--> (~ $S $P) $M) $T2)) ((--> $P $M) (Truth_DecomposePNP $T1 $T2)))
317
+ (= (|- ((--> $S $M) $T1) ((--> (~ $P $S) $M) $T2)) ((--> $P $M) (Truth_DecomposeNNN $T1 $T2)))
318
+ (= (|- ((--> $M $S) $T1) ((--> $M (\u2229 $S $P)) $T2)) ((--> $M $P) (Truth_DecomposePNN $T1 $T2)))
319
+ (= (|- ((--> $M $P) $T1) ((--> $M (\u2229 $S $P)) $T2)) ((--> $M $S) (Truth_DecomposePNN $T1 $T2)))
320
+ (= (|- ((--> $M $S) $T1) ((--> $M (\u222A $S $P)) $T2)) ((--> $M $P) (Truth_DecomposeNPP $T1 $T2)))
321
+ (= (|- ((--> $M $P) $T1) ((--> $M (\u222A $S $P)) $T2)) ((--> $M $S) (Truth_DecomposeNPP $T1 $T2)))
322
+ (= (|- ((--> $M $S) $T1) ((--> $M (\u2212 $S $P)) $T2)) ((--> $M $P) (Truth_DecomposePNP $T1 $T2)))
323
+ (= (|- ((--> $M $S) $T1) ((--> $M (\u2212 $P $S)) $T2)) ((--> $M $P) (Truth_DecomposeNNN $T1 $T2)))
324
+
325
+ ; NAL-4: relation component rules.
326
+ (= (|- ((--> (\xD7 $A $B) $R) $T1) ((--> (\xD7 $C $B) $R) $T2)) ((--> $C $A) (Truth_Abduction $T1 $T2)))
327
+ (= (|- ((--> (\xD7 $A $B) $R) $T1) ((--> (\xD7 $A $C) $R) $T2)) ((--> $C $B) (Truth_Abduction $T1 $T2)))
328
+ (= (|- ((--> $R (\xD7 $A $B)) $T1) ((--> $R (\xD7 $C $B)) $T2)) ((--> $C $A) (Truth_Induction $T1 $T2)))
329
+ (= (|- ((--> $R (\xD7 $A $B)) $T1) ((--> $R (\xD7 $A $C)) $T2)) ((--> $C $B) (Truth_Induction $T1 $T2)))
330
+ (= (|- ((--> (\xD7 $A $B) $R) $T1) ((--> $C $A) $T2)) ((--> (\xD7 $C $B) $R) (Truth_Deduction $T1 $T2)))
331
+ (= (|- ((--> (\xD7 $A $B) $R) $T1) ((--> $A $C) $T2)) ((--> (\xD7 $C $B) $R) (Truth_Induction $T1 $T2)))
332
+ (= (|- ((--> (\xD7 $A $B) $R) $T1) ((--> $C $B) $T2)) ((--> (\xD7 $A $C) $R) (Truth_Deduction $T1 $T2)))
333
+ (= (|- ((--> (\xD7 $A $B) $R) $T1) ((--> $B $C) $T2)) ((--> (\xD7 $A $C) $R) (Truth_Induction $T1 $T2)))
334
+ (= (|- ((--> $R (\xD7 $A $B)) $T1) ((--> $A $C) $T2)) ((--> $R (\xD7 $C $B)) (Truth_Deduction $T1 $T2)))
335
+ (= (|- ((--> $R (\xD7 $A $B)) $T1) ((--> $C $A) $T2)) ((--> $R (\xD7 $C $B)) (Truth_Abduction $T1 $T2)))
336
+ (= (|- ((--> $R (\xD7 $A $B)) $T1) ((--> $B $C) $T2)) ((--> $R (\xD7 $A $C)) (Truth_Deduction $T1 $T2)))
337
+ (= (|- ((--> $R (\xD7 $A $B)) $T1) ((--> $C $B) $T2)) ((--> $R (\xD7 $A $C)) (Truth_Abduction $T1 $T2)))
338
+
339
+ ; NAL-5: negation, conjunction, disjunction, and higher-order decomposition.
340
+ (= (|- ((\xAC $A) $T)) ($A (Truth_Negation $T)))
341
+ (= (|- ((\u2227 $A $B) $T)) ($A (Truth_StructuralDeduction $T)))
342
+ (= (|- ((\u2227 $A $B) $T)) ($B (Truth_StructuralDeduction $T)))
343
+ (= (|- ($S $T1) ((\u2227 $S $A) $T2)) ($A (Truth_DecomposePNN $T1 $T2)))
344
+ (= (|- ($S $T1) ((\u2228 $S $A) $T2)) ($A (Truth_DecomposeNPP $T1 $T2)))
345
+ (= (|- ($S $T1) ((\u2227 (\xAC $S) $A) $T2)) ($A (Truth_DecomposeNNN $T1 $T2)))
346
+ (= (|- ($S $T1) ((\u2228 (\xAC $S) $A) $T2)) ($A (Truth_DecomposePPP $T1 $T2)))
347
+ (= (|- ($A $T1) ((==> $A $B) $T2)) ($B (Truth_Deduction $T1 $T2)))
348
+ (= (|- ($A $T1) ((==> (\u2227 $A $B) $C) $T2)) ((==> $B $C) (Truth_Deduction $T1 $T2)))
349
+ (= (|- ($B $T1) ((==> $A $B) $T2)) ($A (Truth_Abduction $T1 $T2)))
350
+
351
+ ; ---------- Derivation and query engine ----------
352
+ (: NARS.Config.MaxSteps (-> Number))
353
+ (@doc NARS.Config.MaxSteps
354
+ (@desc "Default maximum number of derivation task selections")
355
+ (@params ())
356
+ (@return "100"))
357
+ (= (NARS.Config.MaxSteps) 100)
358
+
359
+ (: NARS.Config.TaskQueueSize (-> Number))
360
+ (@doc NARS.Config.TaskQueueSize
361
+ (@desc "Default active task queue bound")
362
+ (@params ())
363
+ (@return "10"))
364
+ (= (NARS.Config.TaskQueueSize) 10)
365
+
366
+ (: NARS.Config.BeliefQueueSize (-> Number))
367
+ (@doc NARS.Config.BeliefQueueSize
368
+ (@desc "Default belief buffer bound")
369
+ (@params ())
370
+ (@return "100"))
371
+ (= (NARS.Config.BeliefQueueSize) 100)
372
+
373
+ (: NARS.CollapseToList (-> Atom Expression))
374
+ (@doc NARS.CollapseToList
375
+ (@desc "Collect nondeterministic results and convert this engine's comma-headed collapse tuple into a plain expression list")
376
+ (@params ((@param "Nondeterministic query to collapse")))
377
+ (@return "A plain expression list of the collapsed results"))
378
+ (= (NARS.CollapseToList $query)
379
+ (let* (($collapsed (collapse $query))
380
+ ($plain (cdr-atom $collapsed)))
381
+ (exclude-item Empty $plain)))
382
+
383
+ (: StampDisjoint (-> Expression Expression Bool))
384
+ (@doc StampDisjoint
385
+ (@desc "True when two evidence stamps share no evidence item")
386
+ (@params ((@param "First evidence stamp list") (@param "Second evidence stamp list")))
387
+ (@return "Bool indicating whether the stamps are disjoint"))
388
+ (= (StampDisjoint $Ev1 $Ev2)
389
+ (== () (intersection-atom $Ev1 $Ev2)))
390
+
391
+ (: StampConcat (-> Expression Expression Expression))
392
+ (@doc StampConcat
393
+ (@desc "Concatenate a stamp with new evidence and sort it, preserving PeTTa lib_nars' stamp-combination shape")
394
+ (@params ((@param "Base evidence stamp") (@param "Evidence stamp to add")))
395
+ (@return "Sorted combined evidence stamp"))
396
+ (= (StampConcat $stamp $addition)
397
+ (if (== $addition ())
398
+ $stamp
399
+ (sort (append $stamp $addition))))
400
+
401
+ (: BestCandidate (-> Atom %Undefined% Expression %Undefined%))
402
+ (@doc BestCandidate
403
+ (@desc "Return the item in a candidate list with the highest score under an evaluator function")
404
+ (@params ((@param "Unary evaluator function") (@param "Current best candidate") (@param "Candidate list")))
405
+ (@return "The best candidate, or the initial best candidate when the list is empty"))
406
+ (= (BestCandidate $evaluateCandidateFunction $bestCandidate $tuple)
407
+ (max-by-atom $evaluateCandidateFunction $bestCandidate $tuple))
408
+
409
+ (: PriorityRank (-> Expression Number))
410
+ (@doc PriorityRank
411
+ (@desc "Task priority score: the confidence of a sentence, with a low sentinel for the empty candidate")
412
+ (@params ((@param "A Sentence candidate or ()")))
413
+ (@return "Priority score"))
414
+ (= (PriorityRank (Sentence ($x (stv $f $c)) $Ev1)) $c)
415
+ (= (PriorityRank ()) -99999.0)
416
+
417
+ (: PriorityRankNeg (-> Expression Number))
418
+ (@doc PriorityRankNeg
419
+ (@desc "Negated task priority score, used to find the lowest-priority queue item")
420
+ (@params ((@param "A Sentence candidate or ()")))
421
+ (@return "Negated priority score"))
422
+ (= (PriorityRankNeg (Sentence ($x (stv $f $c)) $Ev1)) (- 0.0 $c))
423
+ (= (PriorityRankNeg ()) -99999.0)
424
+
425
+ (: LimitSize (-> Expression Number Expression))
426
+ (@doc LimitSize
427
+ (@desc "Bound a priority queue to fewer than the size limit by dropping the lowest-priority items")
428
+ (@params ((@param "Candidate list") (@param "Size bound")))
429
+ (@return "Bounded candidate list"))
430
+ (= (LimitSize $L $size)
431
+ (top-k-by-atom PriorityRank $size $L))
432
+
433
+ (: NARS.PairInference (-> Expression Expression Expression))
434
+ (@doc NARS.PairInference
435
+ (@desc "Apply the binary inference rules in both premise orders")
436
+ (@params ((@param "First judgement") (@param "Second judgement")))
437
+ (@return "A derived judgement"))
438
+ (= (NARS.PairInference $x $y) (|- $x $y))
439
+ (= (NARS.PairInference $x $y) (|- $y $x))
440
+
441
+ (: NARS.BinaryDerivation (-> Expression Expression Expression Expression))
442
+ (@doc NARS.BinaryDerivation
443
+ (@desc "Derive sentences from one selected task and one belief when their stamps are disjoint")
444
+ (@params ((@param "Selected task judgement") (@param "Selected task evidence stamp") (@param "Belief sentence")))
445
+ (@return "A derived Sentence, or no result when stamps overlap or no rule applies"))
446
+ (= (NARS.BinaryDerivation $x $Ev1 (Sentence $y $Ev2))
447
+ (if (StampDisjoint $Ev1 $Ev2)
448
+ (let $stamp (StampConcat $Ev1 $Ev2)
449
+ (case (NARS.PairInference $x $y)
450
+ ((($T $TV) (Sentence ($T $TV) $stamp)))))
451
+ (empty)))
452
+
453
+ (: NARS.UnaryDerivation (-> Expression Expression Expression))
454
+ (@doc NARS.UnaryDerivation
455
+ (@desc "Derive sentences from one selected task using unary inference rules")
456
+ (@params ((@param "Selected task judgement") (@param "Selected task evidence stamp")))
457
+ (@return "A derived Sentence, or no result when no unary rule applies"))
458
+ (= (NARS.UnaryDerivation $x $Ev1)
459
+ (case (|- $x)
460
+ ((($T (stv $f $c)) (Sentence ($T (stv $f $c)) $Ev1)))))
461
+
462
+ (@doc NARS.Derive
463
+ (@desc "Priority-queue forward derivation over tasks and beliefs")
464
+ (@params ((@param "Task list") (@param "Belief list") (@param "Optional step and queue bounds")))
465
+ (@return "A pair (tasks beliefs) after bounded derivation"))
466
+ (= (NARS.Derive $Tasks $Beliefs $steps $maxsteps $taskqueuesize $beliefqueuesize)
467
+ (if (or (> $steps $maxsteps) (== $Tasks ()))
468
+ ($Tasks $Beliefs)
469
+ (let $selected (BestCandidate PriorityRank () $Tasks)
470
+ (let (Sentence $x $Ev1) $selected
471
+ (let $fromBeliefs (NARS.CollapseToList
472
+ (let $belief (superpose $Beliefs)
473
+ (NARS.BinaryDerivation $x $Ev1 $belief)))
474
+ (let $fromTask (NARS.CollapseToList
475
+ (NARS.UnaryDerivation $x $Ev1))
476
+ (let $derivations (append $fromBeliefs $fromTask)
477
+ (let $_ (trace! (SELECTED $steps (Sentence $x $Ev1)) 42)
478
+ (let $taskCandidates (unique-atom (append $Tasks $derivations))
479
+ (let $withoutSelected (exclude-item $selected $taskCandidates)
480
+ (let $newTasks (LimitSize $withoutSelected $taskqueuesize)
481
+ (let $beliefCandidates (unique-atom (append $Beliefs $derivations))
482
+ (let $newBeliefs (LimitSize $beliefCandidates $beliefqueuesize)
483
+ (NARS.Derive $newTasks
484
+ $newBeliefs
485
+ (+ $steps 1)
486
+ $maxsteps
487
+ $taskqueuesize
488
+ $beliefqueuesize))))))))))))))
489
+
490
+ (= (NARS.Derive $Tasks $Beliefs $maxsteps $taskqueuesize $beliefqueuesize)
491
+ (NARS.Derive $Tasks $Beliefs 1 $maxsteps $taskqueuesize $beliefqueuesize))
492
+
493
+ (= (NARS.Derive $Tasks $Beliefs $maxsteps)
494
+ (NARS.Derive $Tasks $Beliefs $maxsteps (NARS.Config.TaskQueueSize) (NARS.Config.BeliefQueueSize)))
495
+
496
+ (= (NARS.Derive $Tasks $Beliefs)
497
+ (NARS.Derive $Tasks $Beliefs (NARS.Config.MaxSteps)))
498
+
499
+ (: ConfidenceRank (-> Expression Number))
500
+ (@doc ConfidenceRank
501
+ (@desc "Query-answer score: the confidence of a (truth evidence) pair, with zero for the empty candidate")
502
+ (@params ((@param "A query answer ((stv f c) evidence) or ()")))
503
+ (@return "Confidence score"))
504
+ (= (ConfidenceRank ((stv $f $c) $Ev)) $c)
505
+ (= (ConfidenceRank ()) 0)
506
+
507
+ (@doc NARS.Query
508
+ (@desc "Query a term against a NARS knowledge base after bounded forward derivation")
509
+ (@params ((@param "Task list or knowledge base") (@param "Belief list or term") (@param "Term and optional bounds")))
510
+ (@return "The highest-confidence answer as ((stv f c) evidence), or () when no belief matches"))
511
+ ; let-force the candidate list: imported into &self, BestCandidate's Expression-typed argument is not
512
+ ; re-evaluated if it already looks like an Expression, so evaluate NARS.CollapseToList explicitly first.
513
+ (= (NARS.Query $Tasks $Beliefs $term $maxsteps $taskqueuesize $beliefqueuesize)
514
+ (let $candidates
515
+ (NARS.CollapseToList
516
+ (let ($TasksRet $BeliefsRet) (NARS.Derive $Tasks $Beliefs $maxsteps $taskqueuesize $beliefqueuesize)
517
+ (case (superpose $BeliefsRet)
518
+ (((Sentence ($Term $TV) $Ev)
519
+ (case (== $Term $term)
520
+ ((True ($TV $Ev)))))))))
521
+ (BestCandidate ConfidenceRank () $candidates)))
522
+
523
+ (= (NARS.Query $kb $term $maxsteps $taskqueuesize $beliefqueuesize)
524
+ (NARS.Query $kb $kb $term $maxsteps $taskqueuesize $beliefqueuesize))
525
+
526
+ (= (NARS.Query $kb $term $maxsteps)
527
+ (NARS.Query $kb $term $maxsteps (NARS.Config.TaskQueueSize) (NARS.Config.BeliefQueueSize)))
528
+
529
+ (= (NARS.Query $kb $term)
530
+ (NARS.Query $kb $term (NARS.Config.MaxSteps)))
531
+ `,
532
+ pln: `
533
+ ; ---------- Tuple helpers ----------
534
+ (@doc PLN.Force
535
+ (@desc "Evaluate a raw expression call while preserving already-data expression lists")
536
+ (@params ((@param "Atom to force")))
537
+ (@return "The evaluated atom, or the original atom when eval leaves it unreduced"))
538
+ (= (PLN.Force $atom)
539
+ (let $forced (eval $atom)
540
+ (case $forced
541
+ (((eval $raw) $atom)
542
+ ($_ $forced)))))
543
+
544
+ (: clamp (-> Number Number Number Number))
545
+ (@doc clamp
546
+ (@desc "Clamp a number to the inclusive range [min, max]")
547
+ (@params ((@param "Value") (@param "Minimum") (@param "Maximum")))
548
+ (@return "The value bounded by the range"))
549
+ (= (clamp $v $min $max)
550
+ (min $max (max $v $min)))
551
+
552
+ (: TupleConcat (-> Expression Expression Expression))
553
+ (@doc TupleConcat
554
+ (@desc "Concatenate two tuple lists represented as Hyperon expression lists")
555
+ (@params ((@param "First tuple list") (@param "Second tuple list")))
556
+ (@return "The concatenated tuple list"))
557
+ (= (TupleConcat $Ev1 $Ev2)
558
+ (append $Ev1 $Ev2))
559
+
560
+ (: TupleCount (-> Expression Number))
561
+ (@doc TupleCount
562
+ (@desc "Count items in a tuple list")
563
+ (@params ((@param "Tuple list")))
564
+ (@return "The item count"))
565
+ (= (TupleCount $tuple)
566
+ (size-atom $tuple))
567
+
568
+ (: and5 (-> Bool Bool Bool Bool Bool Bool))
569
+ (@doc and5
570
+ (@desc "Five-argument boolean conjunction")
571
+ (@params ((@param "First boolean") (@param "Second boolean") (@param "Third boolean") (@param "Fourth boolean") (@param "Fifth boolean")))
572
+ (@return "True when all five inputs are true"))
573
+ (= (and5 $0 $1 $2 $3 $4)
574
+ (and $0 (and $1 (and $2 (and $3 $4)))))
575
+
576
+ (: min5 (-> Number Number Number Number Number Number))
577
+ (@doc min5
578
+ (@desc "Minimum of five numbers")
579
+ (@params ((@param "First number") (@param "Second number") (@param "Third number") (@param "Fourth number") (@param "Fifth number")))
580
+ (@return "The smallest input"))
581
+ (= (min5 $0 $1 $2 $3 $4)
582
+ (min $0 (min $1 (min $2 (min $3 $4)))))
583
+
584
+ (: /safe (-> Number Number Number))
585
+ (@doc /safe
586
+ (@desc "Division guarded like PeTTa lib_pln: divide only when the denominator is positive")
587
+ (@params ((@param "Numerator") (@param "Denominator")))
588
+ (@return "The quotient, or no result when the denominator is not positive"))
589
+ (= (/safe $A $B)
590
+ (if (> $B 0.0)
591
+ (/ $A $B)
592
+ (empty)))
593
+
594
+ (: negate (-> Number Number))
595
+ (@doc negate
596
+ (@desc "Return 1 minus the argument")
597
+ (@params ((@param "Number")))
598
+ (@return "1 - x"))
599
+ (= (negate $arg)
600
+ (- 1.0 $arg))
601
+
602
+ (: invert (-> Number Number))
603
+ (@doc invert
604
+ (@desc "Return the reciprocal through /safe")
605
+ (@params ((@param "Number")))
606
+ (@return "1 / x, or no result when x is not positive"))
607
+ (= (invert $arg)
608
+ (/safe 1.0 $arg))
609
+
610
+ (: InsertSorted (-> Number Expression Expression))
611
+ (@doc InsertSorted
612
+ (@desc "Insert a numeric item into a sorted tuple list")
613
+ (@params ((@param "Item") (@param "Sorted tuple list")))
614
+ (@return "The sorted tuple list with the item inserted"))
615
+ (= (InsertSorted $x $L)
616
+ (if (== $L ())
617
+ ($x)
618
+ (let* ((($head $tail) (decons-atom $L)))
619
+ (if (< $x $head)
620
+ (TupleConcat ($x $head) $tail)
621
+ (let $inserted (InsertSorted $x $tail)
622
+ (TupleConcat ($head) $inserted))))))
623
+
624
+ (: InsertionSort (-> Expression Expression Expression))
625
+ (@doc InsertionSort
626
+ (@desc "Sort a tuple list. The second argument is preserved for PeTTa lib_pln call compatibility and is ignored by the upstream implementation")
627
+ (@params ((@param "Tuple list") (@param "Ignored accumulator")))
628
+ (@return "Sorted tuple list"))
629
+ (= (InsertionSort $L $Ret)
630
+ (let $items (PLN.Force $L)
631
+ (if (== $items ())
632
+ $Ret
633
+ (let* ((($x $rest) (decons-atom $items))
634
+ ($newRet (InsertSorted $x $Ret)))
635
+ (InsertionSort $rest $newRet)))))
636
+
637
+ (: Without (-> Expression %Undefined% Expression))
638
+ (@doc Without
639
+ (@desc "Remove an item from a tuple list")
640
+ (@params ((@param "Tuple list") (@param "Item to remove")))
641
+ (@return "Tuple list without the item"))
642
+ (= (Without $Tuple $a)
643
+ (exclude-item $a $Tuple))
644
+
645
+ (: ElementOf (-> %Undefined% Expression Bool))
646
+ (@doc ElementOf
647
+ (@desc "Check whether an item is a member of a tuple list")
648
+ (@params ((@param "Item") (@param "Tuple list")))
649
+ (@return "Bool membership result"))
650
+ (= (ElementOf $a $Tuple)
651
+ (is-member $a $Tuple))
652
+
653
+ (: Unique (-> Expression Expression Expression))
654
+ (@doc Unique
655
+ (@desc "Deduplicate a tuple list. The second argument is preserved for PeTTa lib_pln call compatibility and is ignored by the upstream implementation")
656
+ (@params ((@param "Tuple list") (@param "Ignored accumulator")))
657
+ (@return "Deduplicated tuple list"))
658
+ (= (Unique $L $Ret)
659
+ (unique-atom $L))
660
+
661
+ ; ---------- Consistency helpers ----------
662
+ (: smallest-intersection-probability (-> Number Number Number))
663
+ (@doc smallest-intersection-probability
664
+ (@desc "Lower bound for a conditional intersection probability")
665
+ (@params ((@param "Strength of A") (@param "Strength of B")))
666
+ (@return "Clamped lower probability bound"))
667
+ (= (smallest-intersection-probability $As $Bs)
668
+ (clamp (/ (- (+ $As $Bs) 1) $As) 0 1))
669
+
670
+ (: largest-intersection-probability (-> Number Number Number))
671
+ (@doc largest-intersection-probability
672
+ (@desc "Upper bound for a conditional intersection probability")
673
+ (@params ((@param "Strength of A") (@param "Strength of B")))
674
+ (@return "Clamped upper probability bound"))
675
+ (= (largest-intersection-probability $As $Bs)
676
+ (clamp (/ $Bs $As) 0 1))
677
+
678
+ (: conditional-probability-consistency (-> Number Number Number Bool))
679
+ (@doc conditional-probability-consistency
680
+ (@desc "Check PeTTa lib_pln conditional probability bounds")
681
+ (@params ((@param "Strength of A") (@param "Strength of B") (@param "Strength of A implies B")))
682
+ (@return "True when the conditional probability is inside the PLN bounds"))
683
+ (= (conditional-probability-consistency $As $Bs $ABs)
684
+ (and (< 0 $As)
685
+ (and (<= (smallest-intersection-probability $As $Bs) $ABs)
686
+ (<= $ABs (largest-intersection-probability $As $Bs)))))
687
+
688
+ (: Consistency_ImplicationImplicantConjunction (-> Number Number Number Number Number Bool))
689
+ (@doc Consistency_ImplicationImplicantConjunction
690
+ (@desc "Check PeTTa lib_pln implication and implicant conjunction consistency")
691
+ (@params ((@param "Strength of A") (@param "Strength of B") (@param "Strength of C") (@param "Strength of A implies C") (@param "Strength of B implies C")))
692
+ (@return "Bool consistency result"))
693
+ (= (Consistency_ImplicationImplicantConjunction $As $Bs $Cs $ACs $BCs)
694
+ (and5 (> $As 0) (> $Bs 0) (> $Cs 0)
695
+ (<= $ACs (/ $Cs $As))
696
+ (<= $BCs (/ $Cs $Bs))))
697
+
698
+ ; ---------- Truth functions ----------
699
+ ; PeTTa lib_pln leaves STV as a stub so callers can define node truth values.
700
+ (= (STV $stv) (empty))
701
+
702
+ (: Truth_c2w (-> Number Number))
703
+ (@doc Truth_c2w
704
+ (@desc "Convert PLN confidence to evidence weight")
705
+ (@params ((@param "Confidence c")))
706
+ (@return "Evidence weight c / (1 - c), or no result when c is 1"))
707
+ (= (Truth_c2w $c)
708
+ (/safe $c (- 1 $c)))
709
+
710
+ (: Truth_w2c (-> Number Number))
711
+ (@doc Truth_w2c
712
+ (@desc "Convert evidence weight to PLN confidence")
713
+ (@params ((@param "Evidence weight w")))
714
+ (@return "Confidence w / (w + 1)"))
715
+ (= (Truth_w2c $w)
716
+ (/safe $w (+ $w 1)))
717
+
718
+ (: Truth_Deduction (-> Expression Expression Expression Expression Expression Expression))
719
+ (@doc Truth_Deduction
720
+ (@desc "PeTTa lib_pln five-argument PLN deduction truth function")
721
+ (@params ((@param "Truth of P") (@param "Truth of Q") (@param "Truth of R") (@param "Truth of P implies Q") (@param "Truth of Q implies R")))
722
+ (@return "Deductive simple truth value"))
723
+ (= (Truth_Deduction (stv $Ps $Pc)
724
+ (stv $Qs $Qc)
725
+ (stv $Rs $Rc)
726
+ (stv $PQs $PQc)
727
+ (stv $QRs $QRc))
728
+ (if (and (conditional-probability-consistency $Ps $Qs $PQs)
729
+ (conditional-probability-consistency $Qs $Rs $QRs))
730
+ (stv (if (< 0.9999 $Qs)
731
+ $Rs
732
+ (+ (* $PQs $QRs)
733
+ (/safe (* (- 1 $PQs) (- $Rs (* $Qs $QRs))) (- 1 $Qs))))
734
+ (min $Pc (min $Qc (min $Rc (min $PQc $QRc)))))
735
+ (stv 1 0)))
736
+
737
+ (: Truth_Induction (-> Expression Expression Expression Expression Expression Expression))
738
+ (@doc Truth_Induction
739
+ (@desc "PeTTa lib_pln five-argument PLN induction truth function")
740
+ (@params ((@param "Truth of A") (@param "Truth of B") (@param "Truth of C") (@param "Truth of B implies A") (@param "Truth of B implies C")))
741
+ (@return "Inductive simple truth value"))
742
+ (= (Truth_Induction (stv $sA $cA)
743
+ (stv $sB $cB)
744
+ (stv $sC $cC)
745
+ (stv $sBA $cBA)
746
+ (stv $sBC $cBC))
747
+ (stv (+ (/safe (* (* $sBA $sBC) $sB) $sA)
748
+ (* (- 1 (/safe (* $sBA $sB) $sA))
749
+ (/safe (- $sC (* $sB $sBC)) (- 1 $sB))))
750
+ (Truth_w2c (min $cBA $cBC))))
751
+
752
+ (: Truth_Abduction (-> Expression Expression Expression Expression Expression Expression))
753
+ (@doc Truth_Abduction
754
+ (@desc "PeTTa lib_pln five-argument PLN abduction truth function")
755
+ (@params ((@param "Truth of A") (@param "Truth of B") (@param "Truth of C") (@param "Truth of A implies B") (@param "Truth of C implies B")))
756
+ (@return "Abductive simple truth value"))
757
+ (= (Truth_Abduction (stv $sA $cA)
758
+ (stv $sB $cB)
759
+ (stv $sC $cC)
760
+ (stv $sAB $cAB)
761
+ (stv $sCB $cCB))
762
+ (stv (+ (/safe (* (* $sAB $sCB) $sC)
763
+ $sB)
764
+ (/safe (* $sC (* (- 1 $sAB) (- 1 $sCB)))
765
+ (- 1 $sB)))
766
+ (Truth_w2c (min $cAB $cCB))))
767
+
768
+ (: Truth_ModusPonens (-> Expression Expression Expression))
769
+ (@doc Truth_ModusPonens
770
+ (@desc "PeTTa lib_pln modus ponens truth function")
771
+ (@params ((@param "Antecedent truth value") (@param "Implication truth value")))
772
+ (@return "Conclusion truth value"))
773
+ (= (Truth_ModusPonens (stv $f1 $c1) (stv $f2 $c2))
774
+ (stv (+ (* $f1 $f2) (* 0.02 (- 1 $f1)))
775
+ (* $c1 $c2)))
776
+
777
+ (: Truth_SymmetricModusPonens (-> Expression Expression Expression))
778
+ (@doc Truth_SymmetricModusPonens
779
+ (@desc "PeTTa lib_pln symmetric modus ponens truth function")
780
+ (@params ((@param "Source truth value") (@param "Similarity truth value")))
781
+ (@return "Conclusion truth value"))
782
+ (= (Truth_SymmetricModusPonens (stv $sA $cA) (stv $sAB $cAB))
783
+ (let* (($snotAB 0.2)
784
+ ($cnotAB 1.0))
785
+ (stv (+ (* $sA $sAB) (* (* $snotAB (negate $sA)) (+ 1.0 $sAB)))
786
+ (min (min $cAB $cnotAB) $cA))))
787
+
788
+ (: Truth_Revision (-> Expression Expression Expression))
789
+ (@doc Truth_Revision
790
+ (@desc "PeTTa lib_pln heuristic revision of two simple truth values")
791
+ (@params ((@param "First truth value") (@param "Second truth value")))
792
+ (@return "Revised truth value"))
793
+ (= (Truth_Revision (stv $f1 $c1) (stv $f2 $c2))
794
+ (let* (($w1 (Truth_c2w $c1))
795
+ ($w2 (Truth_c2w $c2))
796
+ ($w (+ $w1 $w2))
797
+ ($f (/safe (+ (* $w1 $f1) (* $w2 $f2)) $w))
798
+ ($c (Truth_w2c $w)))
799
+ (stv (min 1.0 $f)
800
+ (min 1.0 (max (max $c $c1) $c2)))))
801
+
802
+ (: Truth_Negation (-> Expression Expression))
803
+ (@doc Truth_Negation
804
+ (@desc "Negate the strength of a simple truth value while preserving confidence")
805
+ (@params ((@param "Truth value")))
806
+ (@return "Negated truth value"))
807
+ (= (Truth_Negation (stv $s $c))
808
+ (stv (- 1.0 $s) $c))
809
+
810
+ (: Truth_inversion (-> Expression Expression Expression))
811
+ (@doc Truth_inversion
812
+ (@desc "PeTTa lib_pln inversion truth function")
813
+ (@params ((@param "Target node truth value") (@param "Link truth value")))
814
+ (@return "Inverted truth value"))
815
+ (= (Truth_inversion (stv $Bs $Bc) (stv $ABs $ABc))
816
+ (stv $ABs (* $Bc (* $ABc 0.6))))
817
+
818
+ (: Truth_equivalenceToImplication (-> Expression Expression Expression Expression))
819
+ (@doc Truth_equivalenceToImplication
820
+ (@desc "Convert an equivalence truth value into an implication truth value")
821
+ (@params ((@param "Truth of A") (@param "Truth of B") (@param "Truth of equivalence A B")))
822
+ (@return "Implication truth value"))
823
+ (= (Truth_equivalenceToImplication (stv $As $Ac) (stv $Bs $Bc) (stv $ABs $ABc))
824
+ (let* (($ConclS (if (< 0.99 (* $ABs $ABc))
825
+ $ABs
826
+ (/safe (* (+ 1.0 (/safe $Bs $As)) $ABs) (+ 1.0 $ABs)))))
827
+ (stv $ConclS $ABc)))
828
+
829
+ (: TransitiveSimilarityStrength (-> Number Number Number Number Number Number))
830
+ (@doc TransitiveSimilarityStrength
831
+ (@desc "PeTTa lib_pln transitive similarity strength helper")
832
+ (@params ((@param "Strength of A") (@param "Strength of B") (@param "Strength of C") (@param "Strength of A similar B") (@param "Strength of B similar C")))
833
+ (@return "Transitive similarity strength"))
834
+ (= (TransitiveSimilarityStrength $sA $sB $sC $sAB $sBC)
835
+ (let* (($T1 (/ (* (+ 1.0 (/ $sB $sA)) $sAB) (+ 1.0 $sAB)))
836
+ ($T2 (/ (* (+ 1.0 (/ $sC $sB)) $sBC) (+ 1.0 $sBC)))
837
+ ($T3 (/ (* (+ 1.0 (/ $sB $sC)) $sBC) (+ 1.0 $sBC)))
838
+ ($T4 (/ (* (+ 1.0 (/ $sA $sB)) $sAB) (+ 1.0 $sAB))))
839
+ (invert (- (+ (invert (+ (* $T1 $T2)
840
+ (* (negate $T1)
841
+ (/safe (- $sC (* $sB $T2)) (negate $sB)))))
842
+ (invert (+ (* $T3 $T4)
843
+ (* (negate $T3)
844
+ (/safe (- $sC (* $sB $T4)) (negate $sB))))))
845
+ 1.0))))
846
+
847
+ (: Truth_transitiveSimilarity (-> Expression Expression Expression Expression Expression Expression))
848
+ (@doc Truth_transitiveSimilarity
849
+ (@desc "PeTTa lib_pln transitive similarity truth function")
850
+ (@params ((@param "Truth of A") (@param "Truth of B") (@param "Truth of C") (@param "Truth of A similar B") (@param "Truth of B similar C")))
851
+ (@return "Transitive similarity truth value"))
852
+ (= (Truth_transitiveSimilarity (stv $As $Ac)
853
+ (stv $Bs $Bc)
854
+ (stv $Cs $Cc)
855
+ (stv $ABs $ABc)
856
+ (stv $BCs $BCc))
857
+ (let* (($ConclS (TransitiveSimilarityStrength $As $Bs $Cs $ABs $BCs))
858
+ ($ConclC (min $ABc $BCc)))
859
+ (stv $ConclS $ConclC)))
860
+
861
+ (: simpleDeductionStrength (-> Number Number Number Number Number Number))
862
+ (@doc simpleDeductionStrength
863
+ (@desc "PeTTa lib_pln simple deduction strength helper")
864
+ (@params ((@param "Strength of A") (@param "Strength of B") (@param "Strength of C") (@param "Strength of A implies B") (@param "Strength of B implies C")))
865
+ (@return "Deduction strength, or no result when consistency checks fail"))
866
+ (= (simpleDeductionStrength $sA $sB $sC $sAB $sBC)
867
+ (if (and (conditional-probability-consistency $sA $sB $sAB)
868
+ (conditional-probability-consistency $sB $sC $sBC))
869
+ (if (< 0.99 $sB)
870
+ $sC
871
+ (+ (* $sAB $sBC)
872
+ (/safe (* (- 1.0 $sAB) (- $sC (* $sB $sBC))) (- 1.0 $sB))))
873
+ (empty)))
874
+
875
+ (: Truth_evaluationImplication (-> Expression Expression Expression Expression Expression Expression))
876
+ (@doc Truth_evaluationImplication
877
+ (@desc "PeTTa lib_pln evaluation implication truth function")
878
+ (@params ((@param "Truth of A") (@param "Truth of B") (@param "Truth of C") (@param "Truth of A implies B") (@param "Truth of A implies C")))
879
+ (@return "Evaluation implication truth value"))
880
+ (= (Truth_evaluationImplication (stv $As $Ac)
881
+ (stv $Bs $Bc)
882
+ (stv $Cs $Cc)
883
+ (stv $ABs $ABc)
884
+ (stv $ACs $ACc))
885
+ (let* (($ConclS (simpleDeductionStrength $Bs $As $Cs $ABs $ACs))
886
+ ($ConclC (* (* 0.9 0.9)
887
+ (min5 $Bc $Ac $Cc $ACc (* 0.9 $ABc)))))
888
+ (stv $ConclS $ConclC)))
889
+
890
+ ; ---------- Inference rules ----------
891
+ (@doc |-
892
+ (@desc "PeTTa lib_pln PLN inference rules")
893
+ (@params ((@param "One or two PLN sentences written as (<term> <truth>)")))
894
+ (@return "A derived sentence written as (<term> <truth>)"))
895
+
896
+ ; Revision.
897
+ (= (|- ($T $T1)
898
+ ($T $T2))
899
+ (let $TV (Truth_Revision $T1 $T2)
900
+ ($T $TV)))
901
+
902
+ ; Modus ponens.
903
+ (= (|- ($A $T1)
904
+ ((Implication $A $B) $T2))
905
+ (let $TV (Truth_ModusPonens $T1 $T2)
906
+ ($B $TV)))
907
+
908
+ ; Guards for link-specific rules. Missing guard facts intentionally leave the rule unreduced.
909
+ (= (SymmetricModusPonensRuleGuard Similarity) True)
910
+ (= (SymmetricModusPonensRuleGuard IntentionalSimilarity) True)
911
+ (= (SymmetricModusPonensRuleGuard ExtensionalSimilarity) True)
912
+
913
+ (= (|- ($A $TruthA)
914
+ (($LinkType $A $B) $TruthAB))
915
+ (if (SymmetricModusPonensRuleGuard $LinkType)
916
+ (let $TV (Truth_SymmetricModusPonens $TruthA $TruthAB)
917
+ ($B $TV))
918
+ (empty)))
919
+
920
+ (= (SyllogisticRuleGuard Inheritance) True)
921
+ (= (SyllogisticRuleGuard Implication) True)
922
+
923
+ (= (|- (($LinkType $A $B) $T1)
924
+ (($LinkType $B $C) $T2))
925
+ (if (SyllogisticRuleGuard $LinkType)
926
+ (let* (($TruthA (STV $A))
927
+ ($TruthB (STV $B))
928
+ ($TruthC (STV $C))
929
+ ($TV (Truth_Deduction $TruthA $TruthB $TruthC $T1 $T2)))
930
+ (($LinkType $A $C) $TV))
931
+ (empty)))
932
+
933
+ (= (|- (($LinkType $C $A) $T1)
934
+ (($LinkType $C $B) $T2))
935
+ (if (SyllogisticRuleGuard $LinkType)
936
+ (let* (($TruthA (STV $A))
937
+ ($TruthB (STV $B))
938
+ ($TruthC (STV $C))
939
+ ($TV (Truth_Induction $TruthA $TruthB $TruthC $T1 $T2)))
940
+ (($LinkType $A $B) $TV))
941
+ (empty)))
942
+
943
+ (= (|- (($LinkType $A $C) $T1)
944
+ (($LinkType $B $C) $T2))
945
+ (if (SyllogisticRuleGuard $LinkType)
946
+ (let* (($TruthA (STV $A))
947
+ ($TruthB (STV $B))
948
+ ($TruthC (STV $C))
949
+ ($TV (Truth_Abduction $TruthA $TruthB $TruthC $T1 $T2)))
950
+ (($LinkType $A $B) $TV))
951
+ (empty)))
952
+
953
+ ; Usage of inheritance for predicates.
954
+ (= (|- ((Evaluation (Predicate $x)
955
+ (List (Concept $C))) $T1)
956
+ ((Inheritance (Concept $S) (Concept $C)) $T2))
957
+ (let $TV (Truth_ModusPonens $T1 $T2)
958
+ ((Evaluation (Predicate $x)
959
+ (List (Concept $S)))
960
+ $TV)))
961
+
962
+ (= (|- ((Evaluation (Predicate $x)
963
+ (List (Concept $C1) (Concept $C2))) $T1)
964
+ ((Inheritance (Concept $S) (Concept $C1)) $T2))
965
+ (let $TV (Truth_ModusPonens $T1 $T2)
966
+ ((Evaluation (Predicate $x)
967
+ (List (Concept $S) (Concept $C2)))
968
+ $TV)))
969
+
970
+ (= (|- ((Evaluation (Predicate $x)
971
+ (List (Concept $C1) (Concept $C2))) $T1)
972
+ ((Inheritance (Concept $S) (Concept $C2)) $T2))
973
+ (let $TV (Truth_ModusPonens $T1 $T2)
974
+ ((Evaluation (Predicate $x)
975
+ (List (Concept $C1) (Concept $S)))
976
+ $TV)))
977
+
978
+ (= (|- ((Not $A) $T))
979
+ (let $TV (Truth_Negation $T)
980
+ ($A $TV)))
981
+
982
+ (= (|- ((Inheritance $A $B) $Truth))
983
+ (let* (($TruthB (STV $B))
984
+ ($TV (Truth_inversion $TruthB $Truth)))
985
+ ((Inheritance $B $A) $TV)))
986
+
987
+ (= (|- ((Implication $A $B) $Truth))
988
+ (let* (($TruthB (STV $B))
989
+ ($TV (Truth_inversion $TruthB $Truth)))
990
+ ((Implication $B $A) $TV)))
991
+
992
+ (= (|- ((Equivalence $A $B) $Truth))
993
+ (let* (($TruthA (STV $A))
994
+ ($TruthB (STV $B))
995
+ ($TV (Truth_equivalenceToImplication $TruthA $TruthB $Truth)))
996
+ ((Implication $A $B) $TV)))
997
+
998
+ (= (|- ((Equivalence $A $B) $Truth))
999
+ (let* (($TruthA (STV $A))
1000
+ ($TruthB (STV $B))
1001
+ ($TV (Truth_equivalenceToImplication $TruthA $TruthB $Truth)))
1002
+ ((Implication $B $A) $TV)))
1003
+
1004
+ (= (|- ((Similarity $A $B) $T1)
1005
+ ((Similarity $B $C) $T2))
1006
+ (let* (($TruthA (STV $A))
1007
+ ($TruthB (STV $B))
1008
+ ($TruthC (STV $C))
1009
+ ($TV (Truth_transitiveSimilarity $TruthA $TruthB $TruthC $T1 $T2)))
1010
+ ((Similarity $A $C) $TV)))
1011
+
1012
+ (= (|- ((Evaluation $A $B) $TruthAB)
1013
+ ((Implication $A $C) $TruthAC))
1014
+ (let* (($TruthA (STV $A))
1015
+ ($TruthB (STV $B))
1016
+ ($TruthC (STV $C))
1017
+ ($TV (Truth_evaluationImplication $TruthA $TruthB $TruthC $TruthAB $TruthAC)))
1018
+ ((Evaluation $C $B) $TV)))
1019
+
1020
+ (= (|- ((Member $A $B) $T1)
1021
+ ((Inheritance $B $C) $T2))
1022
+ (let* (($TruthA (STV $A))
1023
+ ($TruthB (STV $B))
1024
+ ($TruthC (STV $C))
1025
+ ($TV (Truth_Deduction $TruthA $TruthB $TruthC $T1 $T2)))
1026
+ ((Member $A $C) $TV)))
1027
+
1028
+ ; ---------- Derivation and query engine ----------
1029
+ (: PLN.Config.MaxSteps (-> Number))
1030
+ (@doc PLN.Config.MaxSteps
1031
+ (@desc "Default maximum number of derivation task selections")
1032
+ (@params ())
1033
+ (@return "100"))
1034
+ (= (PLN.Config.MaxSteps) 100)
1035
+
1036
+ (: PLN.Config.TaskQueueSize (-> Number))
1037
+ (@doc PLN.Config.TaskQueueSize
1038
+ (@desc "Default active task queue bound")
1039
+ (@params ())
1040
+ (@return "10"))
1041
+ (= (PLN.Config.TaskQueueSize) 10)
1042
+
1043
+ (: PLN.Config.BeliefQueueSize (-> Number))
1044
+ (@doc PLN.Config.BeliefQueueSize
1045
+ (@desc "Default belief buffer bound")
1046
+ (@params ())
1047
+ (@return "100"))
1048
+ (= (PLN.Config.BeliefQueueSize) 100)
1049
+
1050
+ (: PLN.CollapseToList (-> Atom Expression))
1051
+ (@doc PLN.CollapseToList
1052
+ (@desc "Collect nondeterministic results and convert this engine's comma-headed collapse tuple into a plain expression list")
1053
+ (@params ((@param "Nondeterministic query to collapse")))
1054
+ (@return "A plain expression list of collapsed results"))
1055
+ (= (PLN.CollapseToList $query)
1056
+ (let* (($collapsed (collapse $query))
1057
+ ($plain (cdr-atom $collapsed)))
1058
+ (exclude-item Empty $plain)))
1059
+
1060
+ (: StampDisjoint (-> Expression Expression Bool))
1061
+ (@doc StampDisjoint
1062
+ (@desc "True when two evidence stamps share no evidence item")
1063
+ (@params ((@param "First evidence stamp") (@param "Second evidence stamp")))
1064
+ (@return "Bool indicating whether the stamps are disjoint"))
1065
+ (= (StampDisjoint $Ev1 $Ev2)
1066
+ (== () (intersection-atom $Ev1 $Ev2)))
1067
+
1068
+ (: StampConcat (-> Expression Expression Expression))
1069
+ (@doc StampConcat
1070
+ (@desc "Concatenate a stamp with new evidence and sort it")
1071
+ (@params ((@param "Base evidence stamp") (@param "Evidence stamp to add")))
1072
+ (@return "Sorted combined evidence stamp"))
1073
+ (= (StampConcat $stamp $addition)
1074
+ (if (== $addition ())
1075
+ $stamp
1076
+ (let $combined (TupleConcat $stamp $addition)
1077
+ (InsertionSort $combined ()))))
1078
+
1079
+ (: BestCandidate (-> Atom %Undefined% Expression %Undefined%))
1080
+ (@doc BestCandidate
1081
+ (@desc "Return the candidate with the highest score under an evaluator function")
1082
+ (@params ((@param "Unary evaluator function") (@param "Current best candidate") (@param "Candidate list")))
1083
+ (@return "The best candidate, or the initial best candidate when the list is empty"))
1084
+ (= (BestCandidate $evaluateCandidateFunction $bestCandidate $tuple)
1085
+ (max-by-atom $evaluateCandidateFunction $bestCandidate $tuple))
1086
+
1087
+ (: PriorityRank (-> Expression Number))
1088
+ (@doc PriorityRank
1089
+ (@desc "Task priority score: the confidence of a Sentence candidate")
1090
+ (@params ((@param "Sentence candidate or empty sentinel")))
1091
+ (@return "Priority score"))
1092
+ (= (PriorityRank (Sentence ($x (stv $f $c)) $Ev1)) $c)
1093
+ (= (PriorityRank ()) -99999.0)
1094
+
1095
+ (: PriorityRankNeg (-> Expression Number))
1096
+ (@doc PriorityRankNeg
1097
+ (@desc "Negated task priority score, used to find the lowest-priority queue item")
1098
+ (@params ((@param "Sentence candidate or empty sentinel")))
1099
+ (@return "Negated priority score"))
1100
+ (= (PriorityRankNeg (Sentence ($x (stv $f $c)) $Ev1)) (- 0.0 $c))
1101
+ (= (PriorityRankNeg ()) -99999.0)
1102
+
1103
+ (: LimitSize (-> Expression Number Expression))
1104
+ (@doc LimitSize
1105
+ (@desc "Limit a priority queue by removing the lowest-priority item when the accumulator reaches the size bound")
1106
+ (@params ((@param "Candidate list") (@param "Size bound")))
1107
+ (@return "Bounded candidate list"))
1108
+ (= (LimitSize $L $size)
1109
+ (top-k-by-atom PriorityRank $size $L))
1110
+
1111
+ (: PLN.PairInference (-> Expression Expression Expression))
1112
+ (@doc PLN.PairInference
1113
+ (@desc "Apply binary inference rules in both premise orders")
1114
+ (@params ((@param "First judgement") (@param "Second judgement")))
1115
+ (@return "A derived judgement"))
1116
+ (= (PLN.PairInference $x $y) (|- $x $y))
1117
+ (= (PLN.PairInference $x $y) (|- $y $x))
1118
+
1119
+ (: PLN.BinaryDerivation (-> Expression Expression Expression Expression))
1120
+ (@doc PLN.BinaryDerivation
1121
+ (@desc "Derive sentences from one selected task and one belief when their stamps are disjoint")
1122
+ (@params ((@param "Selected task judgement") (@param "Selected task evidence stamp") (@param "Belief sentence")))
1123
+ (@return "A derived Sentence, or no result"))
1124
+ (= (PLN.BinaryDerivation $x $Ev1 (Sentence $y $Ev2))
1125
+ (if (StampDisjoint $Ev1 $Ev2)
1126
+ (let $stamp (StampConcat $Ev1 $Ev2)
1127
+ (case (PLN.PairInference $x $y)
1128
+ ((($T $TV) (let $forcedTV $TV
1129
+ (Sentence ($T $forcedTV) $stamp))))))
1130
+ (empty)))
1131
+
1132
+ (: PLN.UnaryDerivation (-> Expression Expression Expression))
1133
+ (@doc PLN.UnaryDerivation
1134
+ (@desc "Derive sentences from one selected task using unary inference rules")
1135
+ (@params ((@param "Selected task judgement") (@param "Selected task evidence stamp")))
1136
+ (@return "A derived Sentence, or no result"))
1137
+ (= (PLN.UnaryDerivation $x $Ev1)
1138
+ (case (|- $x)
1139
+ ((($T $TV) (let $forcedTV $TV
1140
+ (Sentence ($T $forcedTV) $Ev1))))))
1141
+
1142
+ (@doc PLN.Derive
1143
+ (@desc "Priority-queue forward derivation over tasks and beliefs")
1144
+ (@params ((@param "Task list") (@param "Belief list") (@param "Optional step and queue bounds")))
1145
+ (@return "A pair (tasks beliefs) after bounded derivation"))
1146
+ (= (PLN.Derive $Tasks $Beliefs $steps $maxsteps $taskqueuesize $beliefqueuesize)
1147
+ (if (or (> $steps $maxsteps) (== $Tasks ()))
1148
+ ($Tasks $Beliefs)
1149
+ (let $selected (BestCandidate PriorityRank () $Tasks)
1150
+ (let (Sentence $x $Ev1) $selected
1151
+ (let $fromBeliefs (PLN.CollapseToList
1152
+ (let $belief (superpose $Beliefs)
1153
+ (PLN.BinaryDerivation $x $Ev1 $belief)))
1154
+ (let $fromTask (PLN.CollapseToList
1155
+ (PLN.UnaryDerivation $x $Ev1))
1156
+ (let $derivations (TupleConcat $fromBeliefs $fromTask)
1157
+ (let $_ (trace! (SELECTED $steps (Sentence $x $Ev1)) 42)
1158
+ (let $taskCandidates (TupleConcat $Tasks $derivations)
1159
+ (let $uniqueTasks (Unique $taskCandidates ())
1160
+ (let $withoutSelected (Without $uniqueTasks $selected)
1161
+ (let $newTasks (LimitSize $withoutSelected $taskqueuesize)
1162
+ (let $beliefCandidates (TupleConcat $Beliefs $derivations)
1163
+ (let $uniqueBeliefs (Unique $beliefCandidates ())
1164
+ (let $newBeliefs (LimitSize $uniqueBeliefs $beliefqueuesize)
1165
+ (PLN.Derive $newTasks
1166
+ $newBeliefs
1167
+ (+ $steps 1)
1168
+ $maxsteps
1169
+ $taskqueuesize
1170
+ $beliefqueuesize))))))))))))))))
1171
+
1172
+ (= (PLN.Derive $Tasks $Beliefs $maxsteps $taskqueuesize $beliefqueuesize)
1173
+ (PLN.Derive $Tasks $Beliefs 1 $maxsteps $taskqueuesize $beliefqueuesize))
1174
+
1175
+ (= (PLN.Derive $Tasks $Beliefs $maxsteps)
1176
+ (PLN.Derive $Tasks
1177
+ $Beliefs
1178
+ $maxsteps
1179
+ (PLN.Config.TaskQueueSize)
1180
+ (PLN.Config.BeliefQueueSize)))
1181
+
1182
+ (= (PLN.Derive $Tasks $Beliefs)
1183
+ (PLN.Derive $Tasks $Beliefs (PLN.Config.MaxSteps)))
1184
+
1185
+ (: ConfidenceRank (-> Expression Number))
1186
+ (@doc ConfidenceRank
1187
+ (@desc "Query-answer score: the confidence of a (truth evidence) pair")
1188
+ (@params ((@param "Query answer or empty sentinel")))
1189
+ (@return "Confidence score"))
1190
+ (= (ConfidenceRank ((stv $f $c) $Ev)) $c)
1191
+ (= (ConfidenceRank ()) 0)
1192
+
1193
+ (: PLN.QueryCandidate (-> %Undefined% Expression Expression))
1194
+ (@doc PLN.QueryCandidate
1195
+ (@desc "Return a query answer when a belief Sentence has the requested term")
1196
+ (@params ((@param "Requested term") (@param "Belief sentence")))
1197
+ (@return "A (truth evidence) pair, or no result when the term differs"))
1198
+ (= (PLN.QueryCandidate $term (Sentence ($term $TV) $Ev))
1199
+ ($TV $Ev))
1200
+ (= (PLN.QueryCandidate $term $sentence)
1201
+ (empty))
1202
+
1203
+ (@doc PLN.QueryCandidates
1204
+ (@desc "Collect all belief truth/evidence pairs whose term matches a query after bounded derivation")
1205
+ (@params ((@param "Task list") (@param "Belief list") (@param "Term") (@param "Step and queue bounds")))
1206
+ (@return "A plain expression list of query candidates"))
1207
+ (= (PLN.QueryCandidates $qcTasks $qcBeliefs $qcTerm $qcMaxSteps $qcTaskQueueSize $qcBeliefQueueSize)
1208
+ (let $TasksEval (PLN.Force $qcTasks)
1209
+ (let $BeliefsEval (PLN.Force $qcBeliefs)
1210
+ (let* (($maxstepsEval (+ 0 $qcMaxSteps))
1211
+ ($taskqueuesizeEval (+ 0 $qcTaskQueueSize))
1212
+ ($beliefqueuesizeEval (+ 0 $qcBeliefQueueSize)))
1213
+ (let ($TasksRet $BeliefsRet)
1214
+ (PLN.Derive $TasksEval $BeliefsEval 1 $maxstepsEval $taskqueuesizeEval $beliefqueuesizeEval)
1215
+ (PLN.CollapseToList
1216
+ (let $belief (superpose $BeliefsRet)
1217
+ (PLN.QueryCandidate $qcTerm $belief))))))))
1218
+
1219
+ (@doc PLN.Query
1220
+ (@desc "Query a term against a PLN knowledge base after bounded forward derivation")
1221
+ (@params ((@param "Task list or knowledge base") (@param "Belief list or term") (@param "Term and optional bounds")))
1222
+ (@return "The highest-confidence answer as ((stv f c) evidence), or () when no belief matches"))
1223
+ (= (PLN.Query $ts $bs $term $m $t $b)
1224
+ (let* (($TasksClone (filter-atom $ts $taskItem True))
1225
+ ($BeliefsClone (filter-atom $bs $beliefItem True)))
1226
+ (BestCandidate ConfidenceRank ()
1227
+ (PLN.QueryCandidates $TasksClone
1228
+ $BeliefsClone
1229
+ $term
1230
+ $m
1231
+ $t
1232
+ $b))))
1233
+
1234
+ (= (PLN.Query $k $term $m $t $b)
1235
+ (let $kbClone (filter-atom $k $kbItem True)
1236
+ (BestCandidate ConfidenceRank ()
1237
+ (PLN.QueryCandidates $kbClone
1238
+ $kbClone
1239
+ $term
1240
+ $m
1241
+ $t
1242
+ $b))))
1243
+
1244
+ (= (PLN.Query $k $term $m)
1245
+ (PLN.Query $k $term $m (PLN.Config.TaskQueueSize) (PLN.Config.BeliefQueueSize)))
1246
+
1247
+ (= (PLN.Query $k $term)
1248
+ (PLN.Query $k $term (PLN.Config.MaxSteps)))
1249
+ `
1250
+ };
1251
+
1252
+ // src/index.ts
1253
+ var done = false;
1254
+ function registerLibraries() {
1255
+ if (done) return;
1256
+ for (const [name, src] of Object.entries(LIBRARY_MODULE_SRCS)) {
1257
+ registerBuiltinModule(name, src);
1258
+ }
1259
+ done = true;
1260
+ }
1261
+ registerLibraries();
1262
+ export {
1263
+ LIBRARY_MODULE_SRCS,
1264
+ registerLibraries
1265
+ };