简体   繁体   中英

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. Im new to prolog, so i have issue with my code. 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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