Friday 15 February 2019

Prolog: Get size or length of the list


Write a program that returns number of elements in the list.

We can solve this problem using recursion.

Size of empty list is 0.
size([], 0).

Size of non-empty list is 1 + size of tail list.
size([Head|Tail], L) :- size(Tail,N), L is N+1.

listDemo.pl

size([], 0).
size([Head|Tail], Length) :- size(Tail,TailListLength), Length is TailListLength+1.


1 ?- consult(listDemo).
Warning: c:/users/public/prologexamples/listdemo.pl:2:
        Singleton variables: [Head]
true.

2 ?- size([], X).
X = 0.

3 ?- size([2], X).
X = 1.

4 ?- size([2, 3, 5], X).
X = 3.


Previous                                                 Next                                                 Home

No comments:

Post a Comment