Prolog Operators

Prolog Lists

Built-In Predicates

Miscellaneous

Prolog - Even and Odd Length Finding of A List



In this example, we will see two operations using which we can check whether the list has odd number of elements or the even number of elements. We will define predicates namely, list_even_len(L) and list_odd_len(L).

Checking Even/odd Length of a List

  • If the list has no elements, then that is even length list.

  • Otherwise we take it as [Head|Tail], then if Tail is of odd length, then the total list is even length string.

  • Similarly, if the list has only one element, then that is odd length list.

  • By taking it as [Head|Tail] and Tail is even length string, then entire list is odd length list.

Program (list_misc.pl)

list_even_len([]).
list_even_len([Head|Tail]) :- list_odd_len(Tail).
list_odd_len([_]).
list_odd_len([Head|Tail]) :- list_even_len(Tail).

Output (Checking Odd Length)

| ?- consult('D:/TP Prolog/Sample Codes/list_misc.pl').
compiling D:/TP Prolog/Sample Codes/list_misc.pl for byte code...
D:/TP Prolog/Sample Codes/list_misc.pl:2: warning: singleton variables [Head] for list_even_len/1
D:/TP Prolog/Sample Codes/list_misc.pl:4: warning: singleton variables [Head] for list_odd_len/1
D:/TP Prolog/Sample Codes/list_misc.pl compiled, 3 lines read - 726 bytes written, 3 ms

yes
| ?- list_odd_len([a,2,b,3,c]).

true ? 

yes
| ?- list_odd_len([a,2,b,3]).

no
| ?-

Output (Checking Even Length)

| ?- list_even_len([a,2,b,3]).

true ? 

yes
| ?- list_even_len([a,2,b,3,c]).

no
| ?- 

Explanation

  • list_even_len([]) It is base case for even sized list. A empty list length is considered as even.

  • list_odd_len([_]) It is base case for odd sized list. A List of one element is of odd size.

  • list_even_len([Head|Tail]) :- list_odd_len(Tail). checks a list if size is even or not.

    • list_even_len([Head|Tail]) divides the list where Head represents head element of the list and Tail represents the rest of the list.

    • list_odd_len(Tail) checks the length of the tail of the list as odd sized. If tail is of odd size, the original list size is even.

  • list_odd_len([Head|Tail]) :- list_even_len(Tail). checks a list if size is odd or not.

    • list_odd_len([Head|Tail]) divides the list where Head represents head element of the list and Tail represents the rest of the list.

    • list_even_len(Tail) checks the length of the tail of the list as even sized. If tail is of even size, the original list size is odd.

Advertisements