Basic Prolog (List)
1. How to find last element from a list Code: lastelement([A],A). lastelement([_|A],B):- lastelement(A,B). Output: lastelement([a,b,c,d],X). X = d . 2. How to find n th element of a list Code: element_at(X,[X|_],1). element_at(X,[_|T],Y):- element_at(X,T,Y1), Y is Y1+1. Output: element_at(X,[a,b,c,d],2). X = b . 3. How to check whether the element available or not Code: mem([X|_],X). mem([_|T],X):- mem(T,X). Output: mem([a,b,c,d],a). true . 4. How to print all members Code: mem([X|_],X). mem([_|T],X):- mem(T,X). Output: mem([a,b,c,d],X). X = a ; X = b ; X = c ; X = d ; false. There is a “Prolog” keyword to find member of list. We can use it directly. 4.1. ?- member(X,[a,b,c,d]). X = a ; X = b ; X = c ; X = d. 4.2. ?- member(b,[a,b,c,d]). True 5. How to find the length of the list Code: list_length([],0). list_length([_|T],X):- list_length(T,X1),X is X1+1. O