How to Remove Duplicates in Prolog
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.