HepLib
Loading...
Searching...
No Matches
Sort.cpp
Go to the documentation of this file.
1
6#include "BASIC.h"
7
8namespace HepLib {
9
10 bool ex_less(const ex &a, const ex &b) {
11 static ex_is_less less;
12 if(a.is_equal(b)) return false;
13
14 // numeric
15 if(is_a<numeric>(a) && is_a<numeric>(b)) {
16 auto ab = a-b;
17 auto abr = real_part(ab);
18 if(!is_zero(abr)) return abr<0;
19 else return imag_part(ab)<0;
20 }
21 if(is_a<numeric>(a)) return true;
22 if(is_a<numeric>(b)) return false;
23
24 // symbol/Symbol
25 if(is_a<symbol>(a) && is_a<symbol>(b)) {
26 string sa = ex_to<symbol>(a).get_name();
27 string sb = ex_to<symbol>(b).get_name();
28 return sa < sb;
29 }
30 if(is_a<symbol>(a)) return true;
31 if(is_a<symbol>(b)) return false;
32
33 // lst
34 if(is_a<lst>(a) && is_a<lst>(b)) {
35 auto na = a.nops();
36 auto nb = b.nops();
37 if(na!=nb) return (na<nb);
38 for(int i=0; i<na; i++) {
39 if(a.op(i).is_equal(b.op(i))) continue;
40 return ex_less(a.op(i), b.op(i));
41 }
42 return false;
43 }
44 if(is_a<lst>(b)) return true;
45 if(is_a<lst>(a)) return false;
46
47 return less(a,b);
48 }
54 void sort_vec(exvector & ivec, bool less) {
55 std::sort(ivec.begin(), ivec.end(), [less](const auto &a, const auto &b){
56 if(less) return ex_less(a,b);
57 else return ex_less(b,a);
58 });
59 }
60
67 void sort_vec_by(exvector & ivec, int ki, bool less) {
68 std::sort(ivec.begin(), ivec.end(), [ki,less](const auto &as, const auto &bs){
69 if(less) return ex_less(as.op(ki),bs.op(ki));
70 else return ex_less(bs.op(ki),as.op(ki));
71 });
72 }
73
79 void sort_lst(lst & ilst, bool less) {
80 auto ivec = lst2vec(ilst);
81 sort_vec(ivec,less);
82 for(auto i=0; i<ivec.size(); i++) ilst.let_op(i) = ivec[i];
83 }
84
91 void sort_lst_by(lst & ilst, int ki, bool less) {
92 auto ivec = lst2vec(ilst);
93 sort_vec_by(ivec,ki,less);
94 for(auto i=0; i<ivec.size(); i++) ilst.let_op(i) = ivec[i];
95 }
96
97
98}
int * a
Basic header file.
HepLib namespace.
Definition BASIC.cpp:17
bool ex_less(const ex &a, const ex &b)
Definition Sort.cpp:10
exvector lst2vec(const lst &alst)
convert lst to exvector
Definition BASIC.cpp:911
void sort_lst_by(lst &ilst, int n, bool less=true)
sort the list in less order, or the reverse
Definition Sort.cpp:91
const Symbol as
void sort_vec(exvector &ivec, bool less=true)
sort the list in less order, or the reverse
Definition Sort.cpp:54
void sort_lst(lst &ilst, bool less=true)
sort the list in less order, or the reverse
Definition Sort.cpp:79
void sort_vec_by(exvector &ivec, int n, bool less=true)
sort the list in less order, or the reverse
Definition Sort.cpp:67