Salvan
Salvan

Reputation: 9

Extracting symbols from a given formula

I'm trying to extract symbols from formula. Ex:

?- formula((p v q) & (q v r), U).

U = [p, q, v].

What I've done so far:

simbol_formula([],[]).
simbol_formula(negation X, [X]).
simbol_formula(X or Y, [X,Y]).
simbol_formula(X and Y, [X,Y]).

I believe what I did is correct but incomplete. I am stuck. It obviously works for simple formulas but for more complex formulas it does not. I know I have to define something as simbol_formula(F,U) :-. Using recursion somehow or break the given formula into "smaller" ones.

Upvotes: 0

Views: 47

Answers (1)

mat
mat

Reputation: 40768

The core problem in your case is the use of defaulty data structures.

In your representation, you cannot, by pattern matching alone, distinguish between:

  • a symbol
  • other formulas.

To overcome this shortcoming, I suggest to uniquely mark symbols with the (arbitrary) functor s/1.

For example, the formula (p v q) & (q v r) would be represented as:

(s(p) ∨ s(q)) & (s(q) ∨ s(r))

Then, we can use a DCG to relate formulas to symbols:

symbols(s(X))        --> [X].
symbols(negation(F)) --> symbols(F).
symbols(X ∨ Y)       --> symbols(X), symbols(Y).
symbols(X & Y)       --> symbols(X), symbols(Y).

Sample query:

?- phrase(symbols((s(p) ∨ s(q)) & (s(q) ∨ s(r))), Ls).
Ls = [p, q, q, r].

I leave defining the suitable operators as an exercise, so that the above compiles.

The above can also be used to enumerate formulas, albeit unfairly:

?- phrase(symbols(Formula), Ls).
Formula = s(_G1010),
Ls = [_G1010] ;
Formula = negation(s(_G1012)),
Ls = [_G1012] ;
Formula = negation(negation(s(_G1014))),
Ls = [_G1014] .

Upvotes: 1

Related Questions