Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog -- better way to eliminate duplicate answer in special case?

I was having trouble with these two lines:

list_swizzle(L, [], L).
list_swizzle([], L, L).

The problem was that if the both of the first two arguments are the empty list, the first two statements would both be used, returning the same answer. However, if I put a cut in one, it wrecks backtracking. I eventually put in this line above them:

list_swizzle([], [], []):- !.

And it works. But I was wondering if there is a more elegant solution.

like image 809
Nathan Avatar asked Oct 11 '22 06:10

Nathan


1 Answers

Here's my version:

list_swizzle([H|T], [], [H|T]).
list_swizzle([], L, L).

I'm counting on [] not unifying against [H|T] in the first fact. In other words [] has no T because it's the empty list so the first fact doesn't match goals with a [] in the first arg.

I've run this successfully on SWI-Prolog (Multi-threaded, 32 bits, Version 5.8.2)

$ cat tt.pl

s([H|T], [], [H|T]).
s([], L, L).

....

For help, use ?- help(Topic). or ?- apropos(Word).

?- [tt].
% tt compiled 0.00 sec, 920 bytes
true.

?- s(L,[],[]).
L = [].

?- 
% halt
like image 196
Dafydd Rees Avatar answered Nov 15 '22 12:11

Dafydd Rees