Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing the Results of a Prolog Predicate

Tags:

prolog

How does one evaluate the result of a prolog predicate to pass as an argument? I am trying to write code to reverse pairs of elements in a list:

swap([A,B,C,D,E,F],R).

I want the result:

[B,A,D,C,F,E]

but I get this result:

append(append(append([],[B,A],[D,C],[F,E])))

Here is my code:

swap(L,R) :- swapA(L,[],R).
swapA([],A,A).
swapA([H,H2|T],A,R) :-  swapA(T, append(A,[H2,H]), R).

Thanks.

like image 271
Daniel Sopel Avatar asked Jan 28 '26 18:01

Daniel Sopel


1 Answers

Several things:

  • a variable starts with a capital letter, if you want to differenciate an atom from a variable, wrap it between ': ['A','B','C','D','E','F']
  • you do not need append to successfully implement this predicate. The complexity is way worse when using append.
  • because you do not need append, you do not need 3 arguments either, 2 suffice

Here is a suggestion:

swapA([], []).
swapA([X, Y|T], [Y, X|R]) :- swapA(T, R).

And consider adding another base case if you want your predicate to hold when you have an odd number of elements in your list:

swapA([X], [X]).
like image 141
m09 Avatar answered Feb 01 '26 08:02

m09



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!