# Sorting predicates in PROLOG

**URL:** <https://swi-prolog.discourse.group/t/sorting-predicates-in-prolog/5618>\
**Category:** Help!\
**Tags:** how-to\
**Created:** [July 17, 2022, 7:59pm UTC](https://swi-prolog.discourse.group/t/sorting-predicates-in-prolog/5618 "2022-07-17T19:59:59Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![EricGT](https://avatars.discourse-cdn.com/v4/letter/e/f1d935/32.png) [@EricGT](https://swi-prolog.discourse.group/u/EricGT)\
**Post date:** [July 17, 2022, 9:28pm UTC](https://swi-prolog.discourse.group/t/sorting-predicates-in-prolog/5618/2 "2022-07-17T21:28:06Z")

</div>

This is cross posted on StackOverflow

> <https://stackoverflow.com/questions/73013457/sorting-predicates-in-prolog>

* * *

> [@elfi](#):
>
> I am new to prolog, is there any function to sort predicates ?

Yes.

order\_by/2

> [@Order\_by/2 examples](https://swi-prolog.discourse.group/t/order-by-2-examples/2667):
>
> Here are some examples for order\_by/2 from [library(solution\_sequences)](https://www.swi-prolog.org/pldoc/man?section=solutionsequences) as [test cases](https://www.swi-prolog.org/pldoc/doc_for?object=section(%27packages/plunit.html%27)). :- begin\_tests(order\_by). % run\_tests(order\_by). data(0, 1, 1). data(1, 0, 0). data(0, 0, 0). data(1, 1, 0). data(1, 0, 1). data(0, 0, 1). data(1, 1, 1). data(0, 1, 0). % Bag ordering: same order as data % Item output format: List % Item element order: A,B,C % Data source: facts test(1,[all( Cs == [[[0,1,1],[1,0,0],[0,0,0],[1,1,0],[1,0,1],[0,0,1],[1,1,1],[0,1,0]]] ) ] ) :- bagof([A,B,C], data(A, B, C), Cs…

* * *

Note: order\_by/2 will not work with your predicates because they have different names, i.e. `p1`, `p2`, …  
They need to have the same functor for order\_by/2 to work, e.g.

```prolog
p( 201, 5, 2 ).
p( 301, 1, 2 ).
p( 401, 1, 4 ).
p( 501, 1, 5 ).

```

---

_[View the full topic](https://swi-prolog.discourse.group/t/sorting-predicates-in-prolog/5618)._
