Prolog Operators

Prolog Lists

Built-In Predicates

Miscellaneous

Prolog - Dividing A List



In this operation, we're dividing a list into two lists, and these lists are of approximately same length. So if the given list is [a,b,c,d,e], then the result will be [a,c,e],[b,d]. This will place all of the odd placed elements into one list, and all even placed elements into another list. We will define a predicate, list_divide(L1,L2,L3) to solve this task.

  • If given list is empty, then it will return empty lists.

  • If there is only one element, then the first list will be a list with that element, and the second list will be empty.

  • Suppose X,Y are two elements from head, and rest are Tail, So make two lists [X|List1], [Y|List2], these List1 and List2 are separated by dividing Tail.

Program (list_misc.pl)

list_divide([],[],[]).
list_divide([X],[X],[]).
list_divide([X,Y|Tail], [X|List1],[Y|List2]) :-   list_divide(Tail,List1,List2).

Output - When List is having odd number of elements

| ?- 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 compiled, 2 lines read - 841 bytes written, 4 ms

yes
| ?- list_divide([a,1,b,2,c,3,d,5,e],L1,L2).

L1 = [a,b,c,d,e]
L2 = [1,2,3,5] ? 

yes

Output - When list is having even number of elements

| ?- list_divide([a,b,c,d],L1,L2).

L1 = [a,c]
L2 = [b,d]

yes
| ?- 

Explanation

  • list_divide([],[],[]) It is base case to divide a list. A empty list is divided into two empty lists.

  • list_divide([X],[X],[]). It is another base case where a list of one element is divided into two lists where one is having single element and other is empty.

  • list_divide([X,Y|Tail], [X|List1],[Y|List2]) :- list_divide(Tail,List1,List2). divides the list into two nearly equal sized list using recursive calls.

    • list_divide([X,Y|Tail], [X|List1],[Y|List2]) divides the list where X, Y are first two elements and Tail represents rest of the elements. Second List is having X as head element and a divided result as List1. Third List is having Y as head element and a divided result as List2.

    • list_divide(Tail,List1,List2) makes a recursive call to divide the tail elements into two lists List1 and List2.

Advertisements