2008-05-04

12.3.6 Evaluating a Construct within a String

The CLIPS Basic Programming Guide is (more or less) the only reference you'll ever need for your CLIPS programming needs. It is however sometimes a bit brief. Like the section describing how to add constructs at run-time:

12.3.6 Evaluating a Construct within a String

The build function evaluates the string as though it were entered at the command prompt.

Syntax
(build [string-or-symbol-expression])

where the only argument is the construct to be added. The return value is TRUE if the construct was added (or FALSE if an error occurs).

The build function is not available for binary-load only or run-time CLIPS configurations (see the Advanced Programming Guide).

Example
CLIPS> (clear)
CLIPS> (build "(defrule foo (a) => (assert (b)))")
TRUE
CLIPS> (rules)
foo
For a total of 1 rule.
CLIPS>

It could use a few more examples. Or at least one that is slightly more complex. Personally, I've never used build without wrapping it in a deffunction. But that also introduces the complexity of handling several str-cat calls to build up the definition of the construct in a variable.

Almost all such builder-deffunctions that I've made follow the same basic template
|CLIPS> (deffunction build-foo-deftemplate (?n)
| (bind ?templ (str-cat "(deftemplate foo (slot id)"))
| (loop-for-count (?i ?n)
| (bind ?templ (str-cat ?templ
| " (slot slot" ?i ")")))
| (bind ?templ (str-cat ?templ ")"))
| (build ?templ))
|CLIPS> (build-foo-deftemplate 3)
|TRUE
|CLIPS> (ppdeftemplate foo)
|(deftemplate MAIN::foo
| (slot id)
| (slot slot1)
| (slot slot2)
| (slot slot3))
|CLIPS>
Granted, this example might not be very useful but at least it shows the steps required to incrementally build up a definition in a variable. It's easy to get lost in all of those extra parens but if you've got a decent editor it can match them up for you even though they're embedded in strings.

Inga kommentarer: