ale
ale

Reputation: 11830

Searching Prolog structures

I'm interested in formulae made up from lots of conjunctions (part of a larger problem). I want to write a program that takes something like this:

:- get_params(conj(conj(a,b),c),X)

and returns a list of all the parameters of the conjunctions i.e. X=[a,b,c]. At the moment I can do

:- get_params(conj(a,b),X) to get X=[a,b]

using simple Prolog pattern matching but how would you go about doing things such as

:- get_params(conj(conj(a,b),c),X) to get X=[a,b,c]

It seems really simple but I've been struggling all day!

Upvotes: 1

Views: 280

Answers (2)

mat
mat

Reputation: 40768

Since you are describing a list, consider using DCG notation:

params(conj(A,B)) --> !, params(A), params(B).
params(X)         --> [X].

Example:

?- phrase(params(conj(conj(a,b),c)), Ps).
Ps = [a, b, c].

Upvotes: 4

Little Bobby Tables
Little Bobby Tables

Reputation: 5351

Assuming that all conj functors are binary:

get_params(X, Y, L) :- 
  get_params(X, L1),
  get_params(Y, L2),
  append(L1, L2, L).
get_params(conj(X, Y), L) :-
  get_params(X, Y, L), !.
get_params(A, [A]).

Upvotes: 2

Related Questions