Program 1: Check whether the list has odd number of elements or the even number of elements.
To implement this functionality, we will define predicates list_even_len(L) and list_odd_len(L) while considering the following points.
- An empty list has zero length. Thus, even length list.
- A list with a single element is an odd length list.
- Otherwise, a list [Head | Tail], has odd length if Tail is even length.
- A list [Head | Tail], has even length if Tail is odd length.
Write the following rules in kb5.pl and execute the commands as shown below.

Credit: Copyright (C) 1999-2021 Daniel Diaz
Program 2: Find the maximum element from a list.
Let us define a predicate, list_max_elem(List, Max) considering that,
- If there is only one element in the list, then Max will be that element itself.
- Else, divide the list as [X,Y|Tail]. Recursively find Max of [Y|Tail] and store it into MaxRest. Similarly, find maximum of X and MaxRest, and store it in Max.
To execute this predicate, first write the following rules in kb5.pl and then run the commands in console as shown below.

Credit: Copyright (C) 1999-2021 Daniel Diaz
Program 3: Find the sum of elements of a list.
Here, we will define a predicate, list_sum(List, Sum). If the list is empty, then sum will be 0. Else, list in the form of [Head|Tail], recursively finds sum of the tail and store them into SumTemp. Finally, sum is calculated as, Sum = Head + SumTemp.
For this, write the following rules in kb5.pl and execute the predicate as shown below.




Leave a Reply