Skip to main content

Managing state in Prolog monadically, using DCGs.


Prolog is a beautiful language which makes a lot of irritating rudimentary rule application and search easy. I have found it is particularly nice when trying to deal with compilers which involve rule based transformation from a source language L to a target language L'.

However, the management of these rules generally requires keeping track of a context, and this context has to be explicitly threaded through the entire application, which involves a lot of irritating and error prone sequence variables. This often leads to your code looking something a bit like this:

compile(seq(a,b),(ResultA,ResultB),S0,S2) :- 
  compile(a,ResultA,S0,S1), 
  compile(b,ResultB,S1,S2).

While not the worst thing, I've found it irritating and ugly, and I've made a lot of mistakes with incorrectly sequenced variables. It's much easier to see sequence made explicitly textually in the code.

While they were not designed for this task, but rather for parsing, DCGs turn out to be a convenient way of doing this. In fact, a DCG is just a tool for sequencing variables with a bit of syntactic sugar for manipulating an input list, and an output list, which is generally considered to be the "not yet parsed" remainder.

The simple DCG given below consumes a list of the form [1,2,3].

one --> [1].
two --> [2]. 
three --> [3]. 

eat_list --> one, two, three.


The compiler will take this program and transform it into a number of associated predicates of the same name, with more arguments. The result of this complication phase might look a bit like the following code:

one([1|Rest],Rest). 
two([2|Rest],Rest). 
three([3|Rest],Rest). 

eat_list(In,Out) :- 
   one(In,S0), 
   two(S0,S1), 
   three(S1,Out).

This example looks surprisingly similar to the sort of thing we were doing before! We are threading state through the application, consuming some of it as it goes along.

So how can I easily use DCGs to manipulate state in my application? First, you have to decide what kind of state you want. We're going to opt for a simple option: a list of pairs of the form:

[key1=value1, key2=value2]

We can then introduce a couple of handy helper predicates:

update(C0,C1,S0,S1) :-
    select(C0,S0,C1,S1).

view(C0,S0,S0) :-
    member(C0,S0).

return(S0,_,S0).

Now we can easily thread things together to have a "stateful" approach to manipulation.

Imagine the following term language, a fragment of one cribbed from Dijkstra:

V = atom
Exp = V | integer | Exp + Exp | Exp * Exp
C = C0;C1 | (V := Exp)  

An interpreter for this language might be written in the following way:

eval(A + B, Val) -->
    eval(A,AVal),
    eval(B,BVal),
    {
        Val is AVal + BVal
    }.
eval(A * B, Val) -->
    eval(A,AVal),
    eval(B,BVal),
    {
        Val is AVal * BVal
    }.
eval(A, A) --> {number(A)}.
eval(A, V) -->
    {atom(A)},
    view(A=V).
    
interpret(C0;C1) --> 
    interpret(C0), 
    interpret(C1).
interpret(V:=Exp) -->
    eval(Exp,Val), 
    update(V=_,V=Val).


run :- 
    Term=(
        v := 1 + 3
    ;   w := v + v
    ;   w := w + 1),
    interpret(Term,[v=0,w=0],Result), 
    write(Result).

And presto! You get back the result:

[v=4,w=9]


As we can see, all the messy threading of state is handled very nicely! Perhaps the one rather irritating factor is the need to initialise our variables with some values. This could easily be fixed by changing the update/4 predicate, but we'll leave that as an exercise to the reader.

Comments

Popular posts from this blog

Generating etags automatically when needed

Have you ever wanted M-. (the emacs command which finds the definition of the term under the cursor) to just "do the right thing" and go to the most current definition site, but were in a language that didn't have an inferior process set-up to query about source locations correctly (as is done in lisp, ocaml and some other languages with sophisticated emacs interfaces)?

Well, fret no more. Here is an approach that will let you save the appropriate files and regenerate your TAGS file automatically when things change assuring that M-. takes you to the appropriate place.

You will have to reset the tags-table-list or set it when you first use M-. and you'll want to change the language given to find and etags in the 'create-prolog-tags function (as you're probably not using prolog), but otherwise it shouldn't require much customisation.

And finally, you will need to run etags once manually, or run 'M-x create-prolog-tags' in order to get the initia…

Decidable Equality in Agda

So I've been playing with typing various things in System-F which previously I had left with auxiliary well-formedness conditions. This includes substitutions and contexts, both of which are interesting to have well typed versions of. Since I've been learning Agda, it seemed sensible to carry out this work in that language, as there is nothing like a problem to help you learn a language.

In the course of proving properties, I ran into the age old problem of showing that equivalence is decidable between two objects. In this particular case, I need to be able to show the decidability of equality over types in System F in order to have formation rules for variable contexts. We'd like a context Γ to have (x:A) only if (x:B) does not occur in Γ when (A ≠ B). For us to have statements about whether two types are equal or not, we're going to need to be able to decide if that's true using a terminating procedure.

And so we arrive at our story. In Coq, equality is som…