两个predicates Prolog的追加结果 [英] Prolog Appending Results of Two Predicates
问题描述
:- 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).
在下面的一段$ C $的Ç我help1 predicate将存储在列表中的第N个值。
我的HELP2 predicate将在第一次的N值后,所有的值存储在列表中。
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.
最后,在我的HELP3(TM)功能,我试图追加的结果,我从help1和HELP2得到。但我不能这样做。谁能帮我出或指出什么错误,我做了什么?
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?
推荐答案
首先,定义 help1
太一般了:
?- help1(3,[a,b,c,d,e],Xs).
Xs = [a,b,c] % expected result
; Xs = [a,b,c,d,e] % WRONG!
; false.
这可以通过在predicate定义中删除第二条是固定的:
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).
有关连接两个列表,使用 添加/ 3
。就拿参数顺序照顾!
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.
一件事...其实你不需要定义辅助predicates help1
和 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).
使用示例:
?- help3(2,[a,b,c,d,e,f],R).
R = [c,d,e,f,a,b].
这篇关于两个predicates Prolog的追加结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!