Chapter 3:List and arithmetic

Faiz ul haque Zeya

The first item of list is head of list.The rest of items are called tail of list. Various operations on list are possible. For example whether a element is a member of list.
member(X,[X |Tail]).
member(X,[Head| Tail]):- member(X,Tail).
The first rule says that if first member is X of list is the member we as searching then membership goal is reached.The second rules says if Head is not the member we are searching then apply again the rule for tail.
The rules are applied to following. % c:/member.pl compiled 0.00 sec, 828 bytes 1 ?-
| member(a,[a,b,c]).
Yes
a is the member of list [a,b,c] so is b and c but not d.
2 ?- member(b,[a,b,c]).

Yes
3 ?- member(c,[a,b,c]).

Yes
4 ?-
Yes
5 ?- member(d,[a,b,c]).

No
The answer to which are the members of list a, b,d is :
7 ?- member(X,[a,b,d]).
X = a ;
X = b ;
X = d ;
No
Similary be made for add and delete.
Add a member is add(X,L,[X|L]).
Various arithmetic operators are predefined for example
These include +,-,*,/ and examples include
1 ?- X is 2 + 5.

X = 7

Yes
2 ?- X is 4 -3 .

X = 1
Yes 3 ?- X is 7 * 3.
X = 21
Yes 4 ?- X is 4 /3 . X = 1.33333 Yes
Exercises
  1. Write delete rule for lists.
  2. Write rules for a) 1 + 2/3 b) 3 + 3*3.
  3. Define a list with members 1,2,3.and try whether few numbers are in list.