When a value is returned for a Lisp expression, we may want to bind that value to an Algernon variable, or even to branch on a list of bindings. These capabilities are provided by the special forms :bind and :branch.
Suppose we have a Lisp function that returns a list structure.
(defun lists-of-values () '((1 2 3) (4 5 6) (7 8 9)))
We can evaluate (lists-of-values) and use :bind to capture the resulting list as the binding of an Algernon variable.
(ask '((:bind ?val (lists-of-values))) :comment ":BIND elements of a list.") QUERYING: :BIND elements of a list. Result: Binding: ?val --- ((1 2 3) (4 5 6) (7 8 9)) => T
In a similar construction, :branch will treat the elements of the list as alternate bindings for the variable.
(ask '((:branch ?val (lists-of-values))) :comment ":BRANCH on elements of a list.") QUERYING: :BRANCH on elements of a list. Result (1 of 3): Binding: ?val --- (1 2 3) Result (2 of 3): Binding: ?val --- (4 5 6) Result (3 of 3): Binding: ?val --- (7 8 9) => T
Since the vars argument to :bind and :branch is unified against the value of the Lisp expression, it can be used for pattern matching and destructuring of values.
Suppose we are receiving information that we must filter and analyze.
(defun gossip () '((Tom loves Mary) (Bill hates Joe) (Nancy loves Sam)))
We can branch on each line of the information stream, succeed only at lines with verb ``loves'', and identify subject and object in each line. Here we demonstrate two ways to do this task.
(ask '((:branch ?line (gossip)) (:bind (?subj loves ?obj) '?line)) :comment ":BIND to test and destructure") (ask '((:branch (?subj loves ?obj) (gossip))) :comment ":BRANCH to test and destructure") QUERYING: :BIND to test and destructure Result (1 of 2): Bindings: ?obj --- mary ?subj --- tom ?line --- (tom loves mary) Result (2 of 2): Bindings: ?obj --- sam ?subj --- nancy ?line --- (nancy loves sam) => T QUERYING: :BRANCH to test and destructure Result (1 of 2): Bindings: ?obj --- mary ?subj --- tom Result (2 of 2): Bindings: ?obj --- sam ?subj --- nancy => T