1

Writing sort function, sort(A,B) in Prolog using the built in permutation Prolog function. The sort function holds if B is a sorted version of A.

% sorted holds if list is sorted
sorted([]).
sorted([A]).
sorted([A,B|T]) :- A=<B, sorted([B|T]).

% sort list holds if A is sorted list of B
sort(A,B) :- permutation(A,B), sorted(B).

The problem is: when there are duplicate values in L, R does not include these duplicates.

Output:

?- sort([1,4,2,5,4,4,2], X).
X = [1, 2, 4, 5].

How do I change the sort function so that it doesn't drop duplicates?

1 Answer 1

1

permutation sort doesn't remove duplicates: testing your code

?- sort_([1,4,2,5,4,4,2], X).
X = [1, 2, 2, 4, 4, 4, 5] .

(I renamed to sort_ to avoid the builtin name clash).

But sort/2 does remove duplicates. You can use msort/2

?- msort([1,4,2,5,4,4,2], X).
X = [1, 2, 2, 4, 4, 4, 5].
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.