Question

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!

Was it helpful?

Solution

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]).

OTHER TIPS

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].
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top