John Doe
John Doe

Reputation: 11

swi-prolog truth assignment?

So I have this exercise that I'm stuck on:

A formula is:

tru

fls

variable(V) iff V is an atom.

or(Flist) iff every element in the list is a formula

there are implies, and, neg too. the form looks similar.

We can represent a truth assignment (an assignment of values to variables) by a Prolog list of the form [Var1/Value1, Var2/Value2,...VarN/ValueN]. Write a predicate sub(?F,?Asst,?G) which succeeds iff G is a formula which is a result of substituting the variables of F with corresponding values from the assignment Asst. (You can assume that the truth assignment A is at least partially instantiated).

E.g.

sub(variable(x), [x/tru], tru).
true
sub(or([variable(a),variable(b)]), [a/tru,b/fls], G).
G = or(tru,fls)
true

I've tried

sub(variable(x),[x/value],G):-
    G = variable(value).

But it just returns false.

Edit: Sorry I didn't make the question clear, Can someone explain to me if there's a way to assign values associated with variables in a list to another variable? I think it has something to do with unification.

Upvotes: 1

Views: 682

Answers (1)

repeat
repeat

Reputation: 18726

Variables are placeholders.

Beware of case sensitivity: Prolog variable names start with an uppercase character or underscore, atoms with a lowercase character.

Your code snippet of sub/3 assumes that the list of key-value pairs has exactly a length of one ([x/value]). By using member/2 the lists can have arbitrary length.

When handling n-ary logical connectives like and / or, you probably want a short-circuit implementation that returns as soon as possible. Like so:

sub(tru,_,tru).
sub(fls,_,fls).
sub(variable(X),Assoc,Value) :-
    member(X/Value,Assoc).
sub(or([]),_,fls).
sub(or([X|Xs]),Assoc,V) :-
    sub(X,Assoc,T),
    (  T = tru, V = tru              % short-circuit logical-or
    ;  T = fls, sub(or(Xs),Assoc,V)
    ).

Upvotes: 1

Related Questions