Prolog Operators

Prolog Lists

Built-In Predicates

Miscellaneous

Prolog - Deleting from a List



Prolog provides an inbuilt method delete to delete an element from a List. This method deletes all occurences of the element from the list.

Syntax

delete(List, E, ResultedList)

Where

  • List − Original List.

  • E − element to be removed.

  • ResultedList − Updated List

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

Result = [a,c,d]

(16 ms) yes
| ?- delete([1, 2, 1, 4, 5], 1, Result).

Result = [2,4,5]

yes
| ?- delete([1, 2, 1, 4, 5], 6, Result).

Result = [1,2,1,4,5]

yes
| ?- 

Custom Implementation - Delete from List

We can implement our own method to delete only single occurence of an element from a List. Suppose we have a list L and an element X, we have to delete X from L. So there are three cases −

  • If X is the only element, then after deleting it, it will return empty list.

  • If X is head of L, the resultant list will be the Tail part.

  • If X is present in the Tail part, then delete from there recursively.

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).

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

| ?- list_delete(a,[a,e,i,o,u],NewList).

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

no
| ?- list_delete(a,[a],NewList).

NewList = [] ? ;

NewList = [] ? ;

no
| ?- list_delete(X,[a,e,i,o,u],[a,e,o,u]).

X = i ? ;

(16 ms) no
| ?- list_delete(e,[a,e,e,o,u],NewList).

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

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

(31 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.

Advertisements