How to Remove Duplicates in Prolog

Written by kevin walker
  • Share
  • Tweet
  • Share
  • Email

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.

Skill level:
Moderately Easy

Other People Are Reading


  1. 1

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

  2. 2

    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.

  3. 3

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

Tips and warnings

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

Don't Miss

  • All types
  • Articles
  • Slideshows
  • Videos
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the site, you consent to the use of cookies. For more information, please see our Cookie policy.