DISCOVER
×

How to Remove Duplicates in Prolog

Updated February 21, 2017

Prolog is a declarative programming language commonly used in artificial intelligence and linguistics research. Unlike the more common procedural languages, most Prolog programs are defined as a series of rules and equations, rather than as a series of steps. The following code describes the process to remove duplicates from a list in Prolog.

Open a text editor, such as Notepad, and save your file with the name "remove_dups.pl."

Type the code between the slashes (leaving the slashes themselves out):

/

% remove_dups(+List, -NewList):

% New List isbound to List, but with duplicate items removed.

remove_dups([], []).

remove_dups([First | Rest], NewRest) :-

member(First, Rest),

remove_dups(Rest, NewRest).

remove_dups([First | Rest], [First | NewRest]) :-

not(member(First, Rest)),

remove_dups(Rest, NewRest).

/

The "remove_dups" function is defined as a series of three rules. The first rule ("remove_dups([],[].)") specifies that if the list is empty, nothing should be done; the function should simply return. The second rule specifies that if the first item in the list appears anywhere else in the list, then it should be removed (since it's a duplicate) and processing should continue using the rest of the list by calling the remove_dups function again with the first item in the list left off. The final rule specifies that if the first member of the list is not present elsewhere in the list, it should be kept and processing should continue.

Save your work by hitting "Ctrl" and "S" together.

Tip

While languages such as C and Java usually solve problems using iterative loops, declarative and functional languages like Prolog usually solve problems recursively, or by repeatedly calling the same function on a smaller and smaller set of the total data. Some problems are much easier to solve with recursion, though it can be difficult to learn for programmers used to using only iterative loops to solve problems.

Cite this Article A tool to create a citation to reference this article Cite this Article

About the Author

Kevin Walker is a computer programmer who decided to take a few years out from the corporate life and see the world. He spent a total of six years living abroad and teaching English in China, Korea and Mexico before returning to his home in Texas. He uses his programming and teaching experience to write easy-to-understand computer tutorials.