开发者

Rewrite recursive sicstus prolog function

开发者 https://www.devze.com 2023-04-05 02:34 出处:网络
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)))) ?

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.


Also, consider using DCGs:

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


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):- ....
0

精彩评论

暂无评论...
验证码 换一张
取 消