Re: handling state the database way
"Richard A. O'Keefe" <[email protected]>
| Newsgroups | gmane.comp.ai.prolog.swi |
|---|---|
| Message-ID | <[email protected]> |
On 15/02/2014, at 7:28 AM, Abdallah, Samer wrote:
[To paraphrase:] Why can't I *see* the structure?
May I suggest a module?
First draft:
:- module(single_fact, [
initialise/2,
update/2,
finalise/1
]).
:- meta_predicate
update(+, 2).
:- dynamic store/2.
initialise(Key, Datum) :-
retractall(store(Key,_)),
assert(store(Key, Datum)).
update(Key, Updater) :-
retract(store(Key, Old)),
!, /* green cut */
( call(Updater, Old, New) -> F = true
; New = Old, F = fail
),
assert(store(Key, New)),
F == true.
finalise(Key) :-
retractall(store(Key,_)).
>
> :- dynamic some_pred/1.
> update(Event) :-
> retract(some_pred(OldState)),
> update_something(Event,OldState,NewState),
> assert(some_pred(NewState)).
>
> initialise :
> retractall(some_pred(_)),
> assert(some_pred( <Initial state> )).
This becomes:
initialise :-
single_fact:initialise(<<key>>, <<initial state>>).
update(Event) :-
single_fact:update(<<key>>, update_something(Event)).
>
> Obviously, one could write a library to do this, but I think there might be
> benefit in performance, atomicity and control over backtracking behaviour
> that might come from it being integrated at a lower level, like flag/3.
Yes, but the library stage comes *first*.
By the way, there's a proposal for adding mutable variables to
ISO Prolog, relevant to this. I am afraid that after printing
a copy of the proposal and skimming it, I hurled it into the
nearest paper recycling bin in horror and disgust at the very
idea. But if Prolog _is_ to end up with green worms wriggling
behind its eyes (see Stross's Laundry series for the key to
this metaphor) it would be well if they were the *same* green
worms.
>
> What do you think? Is it the case that the cost of doing unification on the
> state means that it is not worth the small gain of making it a built-in?
The cost of unification is unlikely to be high.
What counts more is how expensive everything *else* the applications
are doing. And really, the only way to find out is to start with a
simple library module and do some profiling.
I will say that any Prolog program that spends a lot of its time
in the single_fact: module will be in desperate need of
restructuring. Or possibly of rewriting in Visual Basic.NET.