Prolog Operators

Prolog Lists

Built-In Predicates

Miscellaneous

Prolog - Inserting into a List



We can insert element in a List in various ways.

  • Inserting at Head of the List

  • Inserting at Tail End of the List

  • Inserting any where in the List

Example - Inserting at Head the List

We can define a method insert_head(X, L, [X|L]) where X is element to be inserted at head of List L, the resulted list is having X is header and L as tail.

Program (list_basics.pl)

insert_head(X, L, [X|L]).

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, 0 lines read - 329 bytes written, 3 ms

yes
| ?- insert_head(a, [b, c, d], Result).

Result = [a,b,c,d]

(15 ms) yes
| ?- 

Example - Inserting at Tail of the List

We can use append() method in insert_head(X, L, R) where X is element to be inserted at head of List L, the resulted list will be R. append() method will append X as a List to the original list resulting a new list having X as tail end.

Program (list_basics.pl)

insert_tail(X, L, R) :- append(L, [X], R)

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, 0 lines read - 395 bytes written, 3 ms

(16 ms) yes
| ?- insert_tail(e, [a, b, c, d], Result).

Result = [a,b,c,d,e]

yes
| ?- 

Example - Inserting into anywhere in the List

This method is used to insert an item X into list L, and the resultant list will be R. So the predicate will be in this form list_insert(X, L, R). So this can insert X into L in all possible positions. If we see closer, then there are some observations.

  • If we perform list_insert(X,L,R), we can use list_delete(X,R,L), so delete X from R and make new list L.

Program (list_basics.pl)

list_delete(X, [X], []).
list_delete(X,[X|L1], L1).
list_delete(X, [Y|L2], [Y|L1]) :- list_delete(X,L2,L1).
list_insert(X,L,R) :- list_delete(X,R,L).

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, 3 lines read - 917 bytes written, 3 ms

(16 ms) yes
| ?- list_insert(a,[e,i,o,u],NewList).

NewList = [a,e,i,o,u] ? a

NewList = [e,a,i,o,u]

NewList = [e,i,a,o,u]

NewList = [e,i,o,a,u]

NewList = [e,i,o,u,a]

NewList = [e,i,o,u,a]

(47 ms) no
| ?- 

Explanation

  • list_delete(X, [X], []) is base case to delete an item from single element list making it empty.

  • list_delete(X,[X|L1], L1) covers the case where X is head of the list

  • list_delete(X, [Y|L2], [Y|L1]) :- list_delete(X,L2,L1) is recursive call where X is not head element of the list.

  • list_insert(X,L,R) :- list_delete(X,R,L) is a call to list_delete() method to remove X from R and provide L as a resulted List.

Advertisements