Friday 15 February 2019

Prolog: Lists


List is an ordered sequence of elements. A list can be either empty (or) a structure that contain head and tail components. Tail is always set to empty list.

What elements a list contains?
A list can contain constants, variable, structures, other lists.

How to define an empty list?
[] used to define an empty list. An empty list has neither a head nor a tail.

List with element a
.(a, [])

List that contain elements a and b.
.(a, .(b, []))

List that contain elements a, b and c.
.(a, .(b, .(c, [])))

As you see above examples, [] is used to specify the tail of the list. As you see this ‘.’ Notation is little complex, Prolog come up with another notation to work with lists, where elements are enclosed by brackets and separated by commas.

Syntax
[element1, element2, ….elementN]

Example
[2, 3, 5, 7]
[krishna, [cricket, chess]]

Pattern matching
[X|Y]
A pattern of above form maps, X to head of the list, and Y to the tail of the list.

1 ?- assert(evenNumbers([2, 4, 6, 8, 10])).
true.

2 ?- evenNumbers([X|Y]).
X = 2,
Y = [4, 6, 8, 10].

3 ?- evenNumbers([X, Y|Z]).
X = 2,
Y = 4,
Z = [6, 8, 10].

4 ?- evenNumbers([A, B, C, D, E]).
A = 2,
B = 4,
C = 6,
D = 8,
E = 10.


Example 1: [a,b,c] unifies with [Head|Tail] resulting in Head=a and Tail=[b,c]
6 ?- assert(list1([a, b, c])).
true.

7 ?- list1([Head|Tail]).
Head = a,
Tail = [b, c].


Example 2: [a] unifies with [Head|Tail] resulting in Head=a and Tail=[]
8 ?- assert(list1([a])).
true.

9 ?- list1([Head|Tail]).
Head = a,
Tail = [b, c] .


Example 3: [a,b,c] unifies with [a|Tail] resulting in Tail=[b,c].
11 ?- assert(list1([a, b, c])).
true.

12 ?- list1([a|Tail]).
Tail = [b, c] .


Example 4: [a,b,c] doesn't unify with [b|T]
14 ?- assert(list1([a, b, c])).
true.

15 ?- list1([b|Tail]).
false.


Example 5: Map a fact with list expression mapping
23 ?- assert(plays(krishna, [cricket, football, tennis])).
true.

24 ?- plays(X, Y).
X = krishna,
Y = [cricket, football, tennis].

25 ?- plays(X, [Y|Z]).
X = krishna,
Y = cricket,
Z = [football, tennis].

26 ?- plays(X, [Sport1, Sport2, Sport3]).
X = krishna,
Sport1 = cricket,
Sport2 = football,
Sport3 = tennis.

27 ?- plays(X, [Sport1, Sport2, Sport3, Sport4]).
false.

Example 6:  Consider the following fact.

fact1([A|B], A, B)).


Let's see what happens when we ask some simple queries.

1 ?- assert(fact1([A|B], A, B)).
true.

2 ?- fact1([1, 2, 3, 4], X, Y).
X = 1,
Y = [2, 3, 4].

3 ?- fact1([1], X, Y).
X = 1,
Y = [].

4 ?- fact1([], X, Y).
false.



Previous                                                 Next                                                 Home

No comments:

Post a Comment