简体   繁体   English

如何编写序言谓词,以使用conc(串联)操作修剪列表中的前N个元素

[英]How to write a prolog predicate to trim first N elements from a List using conc (concatenation) operation

trim(L1,N,L2) which is true if L2 contains the first N elements of L1 

I'm required to write the prolog code using the relation conc. 我需要使用conc关系编写序言代码。 Im new to prolog, so i have issue with my code. 我是prolog的新手,所以我的代码有问题。 Can somebody correct me? 有人可以纠正我吗?

trim(L1, N, L2):- conc(L2,T,L1), length(L2,N),length(L1,N2), N2>= N

Most people have written the code using append and recurssion too. 大多数人也使用附加和递归编写了代码。 Please be kind enough to help me to use conc. 请足够帮助我使用conc。

trim(L1,N,L2):-conc(L3,_,L1),conc(L2,_,L3),length(L2,N),!.

You are nearly there. 你快到了。 Just make 'T' anonymous and you are good to go. 只需将“ T”设为匿名,您就可以使用了。

conc([],L,L).
conc([Head|L1],L2,[Head|L]):-conc(L1,L2,L).
trim(L1,N,L2) :-conc(L2,_,L1) ,length(L2,N).

And ask queries. 并询问。

?- trim([1,2,3],1,X).   
X = [1] ;

?- trim([1,2,3],0,X).
X = [] ;

?- trim([1,2,3],2,[1,2]).
true.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM