Prolog Appending Results of Two Predicates

2019-08-02 20:27发布

问题:

:- import append/3 from basics.


    help1(0,L,[]).
    help1(_,[],[]).
    help1(N,[X|Xs],[X|Res]):- N2 is N - 1, help1(N2,Xs,Res).

    help2(0,L,L).
    help2(N,[X|Xs],Res):- N2 is N - 1, help2(N2,Xs,Res).


    help3(N,L,R):- help1(N,L,R) append help2(N,L,R).

In the following piece of code my help1 predicate will store the first N values in a list. My help2 predicate will store all the values after the first N values in a list.

Finally in my help3 function i am trying to append the results i get from help1 and help2. But i am not able to do so. Can anyone help me out or point out what mistake i have done?

回答1:

First, the definition of help1 is too general:

?- help1(3,[a,b,c,d,e],Xs).
  Xs = [a,b,c]                   % expected result
; Xs = [a,b,c,d,e]               % WRONG!
; false.

This can be fixed by removing the second clause in the predicate definition:

help1(0,_ ,[]).
help1(_,[],[]) :- false.         % too general
help1(N,[X|Xs],[X|Res]) :- 
   N2 is N-1,
   help1(N2,Xs,Res).

For concatenating two lists, use append/3. Take care of the argument order!

help3(N,L,R) :-
   help1(N,L,R1),
   help2(N,L,R2),
   append(R2,R1,R).

Done! Let's try it:

?- help3(2,[a,b,c,d,e,f],R).
  R = [c,d,e,f,a,b]              % OK! works as expected
; false.

One more thing... actually you don't need to define the auxiliary predicates help1 and help2.

Simply use append/3 and length/2 like this:

help3(N,L,R) :-
   length(Prefix,N),
   append(Prefix,Suffix,L),
   append(Suffix,Prefix,R).

Sample use:

?- help3(2,[a,b,c,d,e,f],R).
R = [c,d,e,f,a,b].


标签: prolog append