Confituur
Confituur

Reputation: 495

Sort tuples in Prolog

When I sort [(101,a),(42,b),(85,b)] is Prolog with sort([(101,a),(42,b),(85,b)],X). is get X = [ (42, b), (85, b), (101, a)]. But how come? Does Prolog recognize the tuples and sort them on the first element and then on the second element?

Upvotes: 1

Views: 1799

Answers (2)

user1812457
user1812457

Reputation:

You should really simply look at the exact documentation of the Prolog you are using. In SWI-Prolog, for example, sorting is on "standard order". For compound terms (as you are using), it is first arity, then name, then recursively arguments. So in your case, yes, it is sorted first on first and then on second argument.

By the way, ISO sort should remove duplicates, not that you get surprised by it.

And strictly speaking, there are no "tuples" in Prolog. What you have there is the functor , with arity 2 (or, ,/2). Look at this:

2 ?- write_canonical((42, b)).
','(42,b)
true.

Upvotes: 3

Trylks
Trylks

Reputation: 1498

Your assumption seems reasonable. We can check some documentation, personally I like the documentation for ciao.

See page 235, then page 115. Notice you could also sort by keys.

You should be aware that some people consider using this kind of predicates (non-declarative) a bad practice. Basically there are two terms in this predicate, one must be grounded and the other one must not, so in fact this is a function and not a logical predicate. Those worried for the "purity" of logic programming would probably find a workaround not to use that.

Upvotes: -1

Related Questions