简体   繁体   中英

Prolog unique value in list

I learing Prolog language for exam at college and I don't know how to create function which: check unique values in list. I mean, if each value in list are unique function return true, otherwise return false. eg.

[1,2,3,5] - true
[1,2,2,4] - false

Header for this function is uniqueValues(X) X - mean list. I really don't know this language and if anyone can explain me how to create this function will be great. Thanks in advence for help

Not knowing Prolog, this is going to be a bit of a haul, but let's give it a shot. In Prolog, functions work by recursion rather than iteration. For list processing, this means (in general) you have to decide how to handle the empty list and how to handle an element in front of some other list. So first, you need to make a decision about the empty list.

unique([]).

This says "empty lists are unique." This is a helpful property.

The recursive case assumes that you already know how to handle the rest of the list. In "ordinary" recursive list processing predicates like this, you tend to have this kind of structure:

foo([X|Xs]) :- /* do something with X */, foo(Xs).

The foo(Xs) there is saying, "and run this same thing on whatever's left." So the question we have to ask is, how do we know if a list that starts with X and ends with Xs is unique? Well, we can make sure that X is unique my ensuring it doesn't occur else where in the list. Like this:

unique([X|Xs]) :- \+ memberchk(X, Xs).

Consider your example [1,2,3,4] . The first time in, X = 1 and Xs = [2,3,4]. \\+ means "not" in Prolog, and memberchk/2 tells you whether something is in a list. So memberchk(1, [2,3,4]) will fail and the \\+ will turn that failure into success. This is good! Also, with [1,2,1] , X will equal 1 and Xs will equal [2,1], the memberchk/2 will succeed, and then be negated into a failure. This is probably what we want!

Putting that together with the recursive call, you get this for the entire predicate:

unique([]).
unique([X|Xs]) :- \+ memberchk(X, Xs), unique(Xs).
  1. Empty lists are unique.
  2. Lists that are not empty ([X|Xs]) are unique if:
    1. Xs does not contain X, and
    2. Xs is also unique

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM