Find the last element of a list. % P01 (*): Find the last element of a list % my_last(X,L) :- X is the last element of the list L % (element,list) (?,?) % Note: last(?Elem, ?List) is predefined my_last(X,[X]). my_last(X,[_|L]) :- my_last(X,L). Find the last but one element of a list. % P02 (*): Find the last but one element of a list % last_but_one(X,L) :- X is the last but one element of the list L % (element,list) (?,?) last_but_one(X,[X,_]). last_but_one(X,[_,Y|Ys]) :- last_but_one(X,[Y|Ys]). Find the K'th element of a list. % P03 (*): Find the K'th element of a list. % The first element in the list is number 1. % element_at(X,L,K) :- X is the K'th element of the list L % (element,list,integer) (?,?,+) % Note: nth1(?Index, ?List, ?Elem) is predefined element_at(X,[X|_],1). element_at(X,[_|L],K) :- K > 1, K1 is K - 1, element_at(X,L,K1). Find the number of elements of a list. % P04 (*): Find the number of elements of a list. % my_length(L,N) :- the list L contains N elements % (list,integer) (+,?) % Note: length(?List, ?Int) is predefined my_length([],0). my_length([_|L],N) :- my_length(L,N1), N is N1 + 1.
Comentariul tau va fi primul
Fituici: Exemple prolog Obiect: Nu este specificat