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

Teagrey

I was ironing my shirt today, which I almost never do. Because of this I don't have an ironing board so I tried to make a make-shift ironing board on my floor using a towel and some books. I grabbed the heaviest books on the nearest shelf, which happened to be Organic Chemistry, Stalingrad and an annotated study bible containing the old and new testament. As I pulled out the bible, a flower fell out which had been there for over 17 years now. I know that because it was put there by my first wife, Daniel, who killed herself in April about 17 years ago. It fell from Thessalonians to which it had been opened partially. Highlighted was the passage: "Ye are all sons of the light and sons of the day." I guess the passage gave her solace. Daniel was a complicated woman. She had serious mental health issues which plagued her for her entire life. None of them were her fault. She was dealt an absolutely awful hand in life, some truly nasty cards. She had some considerable c

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