Prolog Operators

Prolog Lists

Built-In Predicates

Miscellaneous

Prolog - Getting Length of A List



Length Calculation

We can define our own custom implementation of membership operation as shown below −

We will define one predicate to do this task. Suppose the predicate name is list_length(L,N). This takes L and N as input argument. This will count the elements in a list L and instantiate N to their number. As was the case with our previous relations involving lists, it is useful to consider two cases −

  • If list is empty, then length is 0.

  • If the list is not empty, then L = [Head|Tail], then its length is 1 + length of Tail.

Program (list_basics.pl)

% Base Case
list_length([],0).
% recursive Case
list_length([_|TAIL],N) :- list_length(TAIL,TailLength), N is TailLength + 1.

Output

| ?- consult('D:/TP Prolog/Sample Codes/list_basics.pl').
compiling D:/TP Prolog/Sample Codes/list_basics.pl for byte code...
D:/TP Prolog/Sample Codes/list_basics.pl compiled, 1 lines read - 657 bytes written, 4 ms

(31 ms) yes
| ?- list_length([a,b,c], X).

X = 3

yes

Checking Length of Empty List

| ?- list_length([], X).

X = 0

yes
| ?-

Explanation

  • list_length([],0) represents the base case of the recursive call. In case list is empty, 0 is returned.

  • list_length([_|TAIL],N) :- list_length(TAIL,TailLength), N is TailLength + 1 represents the recursive case.

    • [_|TAIL] is for a non-empty list where _ represents the head of the list and TAIL is representing the rest of the list.

    • list_length(TAIL,TailLength) makes a recursive call to get the length of tail of the list.

    • N is TailLength + 1 is to get final length as N which is 1 plus the length of the tail of the list.

Advertisements