Yunfeng Zhao
Yunfeng Zhao

Reputation: 11

How to define sort(List,Sorted) in Prolog

How to define the predicate sort(List,Sorted) in Prolog? E.g., sort([3,2,4],[2,3,4]) returns true. I know there is a built-in predicate of this, but I want to know how to define it.

Upvotes: 1

Views: 1719

Answers (1)

user1812457
user1812457

Reputation:

This is not an answer, but a few suggestions that are too long for a comment.

You probably realize that, but still, keep in mind that defining your sort is purely an exercise with the purpose of learning Prolog syntax. You should always use the library sort if you actually need to sort stuff.

Then, "... but I want to know how to define it": What does that mean? Does it mean that you have chosen a sorting algorithm, but you are not sure about how to implement it in Prolog? Or that you have trouble choosing one of several algorithms? Or that you don't know what sorting algorithms exist?

And a suggestion: when choosing a sorting algorithm, prefer one that is meant to be used with singly linked lists. Prolog lists are quite similar to singly linked lists.

And another suggestion: look at existing code (as one commenter nicely pointed out), and also look at the library code of one of the free Prolog implementations. For example, here is the full code of a sort available from SWI-Prolog. It is easy to find, if you just spend a few minutes searching instead of immediately asking for help.

Upvotes: 2

Related Questions