Re: goal_expansion
"Richard A. O'Keefe" <[email protected]>
| Newsgroups | gmane.comp.ai.prolog.swi |
|---|---|
| Message-ID | <[email protected]> |
On 9/02/2014, at 1:46 PM, Jonathon Doran wrote:
> I would very much like to see a simple example of the use of goal_expansion.
>
> I have a large program, and I would like to make a series of changes. I see that I am following the same pattern each time, and if I were writing in another language I would consider creating a macro.
Why use a macro rather than a little predicate?
With an actual named predicate, you can profile it, you can
set spypoints on it, you can see it in a backtrace, all sorts
of stuff.
The example you gave is a perfect example where a
normal call to a normal (but maybe small) predicate
is the right thing to do.
Goal_expansion is for things that cannot or should not be
implemented as ordinary procedure calls. For example,
you could have
goal_expansion(Term ct_is Expr, Expansion) :-
catch(Value is Expr, Error, true),
( var(Error) ->
( Term = Value -> Expansion = true
; Expansion = (Term = Value)
; nonvar(Error), Expansion = (Term is Expr)
).
With this definition, Term ct_is Expr tries to evaluate
Expr at preprocessing time. If that fails, the source
form is replaced by a runtime Term is Expr. If Expr
can be evaluated, the preprocessor tries to unify its
value with Term. If that succeeds, there is no
runtime code (true). If that fails, the expansion is
Term = Value so that the failure will occur at run time.
You could use this for something like
X ct_is cos(0.6*pi),
Y ct_is sin(0.6*pi),
If the goal is to replace certain patterns of code with
a simple form, this is not a task for macros in any
language, but a task for "folding" (the opposite of
unfolding). I had an experimental Prolog structure editor
where you could manually specify a fold to be performed,
but I lost the code years ago.