[1,2,3,4].[].[H | T], where H is a list element and T is a list.[1,2,3 | T].last([H],H).
last([_ | T], V) :- last(T, V).
?- last([1,2],X).
The last element of a list:
last([H],H).
last([_ | T], V) :- last(T, V).
What happens if I ask for last([],X)?
A. pattern match exception.
B. Prolog says false.
C. Prolog says true, X = [].
D. Prolog says true, X = ???.
The last element of a list:
last([H],H).
last([_ | T], V) :- last(T, V).
What happens if I ask for last([],X)?
A. pattern match exception
B. Prolog says false. ✓
C. Prolog says true, X = [].
D. Prolog says true, X = ???.
= operator is used up by unification.
?- A = 1+2.
?- 1+2 = 3.
?- A = money+power.
is operator¶The “is” operator tells prolog to evaluate the righthand expression numerically and unify with the left.
?- X is 1, A is X+2, X is 2.
?- A is money+power.
is operator¶The RHS must be a ground term (no variables).
?- A is B+2.
?- 3 is B+2.
There is support for +,*, /, <, =<, >, >=,etc.
?- X is 20/20.
Compute the length of a list.
len([],0).
len([H | T], N) :- len(T,M), N is M+1.
?- len([1,2,3],X).
The way prolog produces results for the given query is through Backtracking.
len([],0).
len([H | T], N) :- len(T,M), N is M+1.
?- len([1,2],X).
X = 2 .
What is the first result of query len(A,2)?
What is the first result of query len(A,2)?
len([],0).
len([H | T], N) :- len(T,M), N is M+1.
?- len(A,2).
A = [h1,h2] ;
...
What is the second result of query len(A,2)?
What is the second result of query len(A,2)?
len([],0).
len([H | T], N) :- len(T,M), N is M+1.
?- len(A,2).
?- len(A,2) {1}.
len uses O(N) stack space.
len2(List, Acc, Len) such that len2(List, Acc, Len) is true if the sum of the length of List and Acc is euivalent to Len.len2([],Acc,Acc).
len2([H|T],Acc,N) :- M is Acc+1, len2(T,M,N).
?- len2([1,2],0,X).
len2([],Acc,Acc).
len2([H|T],Acc,N) :- M is Acc+1, len2(T,M,N).
len3(L,X) :- len2(L,0,X).
?- len3([1,2,3],X).
e.g. append([1,2], [3,4], [1,2,3,4])
append([],Q,Q).
append([H | P], Q, [H | R]) :- append(P, Q, R).
?- append(Y,X,[1,2,3,4]).
Compute the sum of the list. This is the example we saw in the first Prolog lecture.
sum([],0).
sum([H | T], N) :- sum(T,M), N is M+H.
?- sum([1,2,3],X).
?- sum(X,0) {1}.
<-------X-------->
+-------------------------------+
| | S | |
+-------------------------------+
<--------------Z---------------->
Prefix and Suffix of list can be defined using append.
prefix(X,Z) :- append(X,Y,Z).
suffix(Y,Z) :- append(X,Y,Z).
?- prefix(X,[1,2,3]).
?- suffix(X,[1,2,3]).