keyser
keyser

Reputation: 19199

Rewrite recursive sicstus prolog function

My goal is to have this input:

L = [a,b,c], build_tree(L,T).

With this output:

L = [1,30,kth,5],
T = b(l(a),b(l(b),b(l(c)))) ? 

yes

And with this code, that counts the number of leaves in a tree:

leaves(l(X), [X]).
leaves(b(L1,L2),V):-
    leaves(L1,V1),
    leaves(L2,V2),
    append(V1,V2,V).

I can get the desired output by simply giving the function a list instead of a tree as input, eg:

L = [a,b,c], leaves(T,L).

The only problem here is that it takes the arguments in the wrong order (i.e. build_tree(T,L) instead of build_tree(L,T)).

So, how can I produce the same result, but simply swap the input arguments? I've tried every "obvious" solution (swapping around variables), but I'm guessing that it might not be as easy as it seems since it's a recursive method.

Upvotes: 1

Views: 215

Answers (2)

mat
mat

Reputation: 40778

Also, consider using DCGs:

leaves(l(X))     --> [X].
leaves(b(T1,T2)) --> leaves(T1), leaves(T2).

Upvotes: 2

thanos
thanos

Reputation: 5858

if you have a predicate and want to re-orded the arguments, the simplest way (imo) is to write a wrapper predicate:

my_foo(X,Y,Z):-
    foo(Y,Z,X).

foo(X,Y,Z):- ....

Upvotes: 1

Related Questions