-
-
Notifications
You must be signed in to change notification settings - Fork 137
/
order.gleam
133 lines (125 loc) 路 1.94 KB
/
order.gleam
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/// Represents the result of a single comparison to determine the precise
/// ordering of two values.
///
pub type Order {
/// Less-than
Lt
/// Equal
Eq
/// Greater than
Gt
}
/// Inverts an order, so less-than becomes greater-than and greater-than
/// becomes less-than.
///
/// ## Examples
///
/// ```gleam
/// > negate(Lt)
/// Gt
/// ```
///
/// ```gleam
/// > negate(Eq)
/// Eq
/// ```
///
/// ```gleam
/// > negate(Lt)
/// Gt
/// ```
///
pub fn negate(order: Order) -> Order {
case order {
Lt -> Gt
Eq -> Eq
Gt -> Lt
}
}
/// Produces a numeric representation of the order.
///
/// ## Examples
///
/// ```gleam
/// > to_int(Lt)
/// -1
/// ```
///
/// ```gleam
/// > to_int(Eq)
/// 0
/// ```
///
/// ```gleam
/// > to_int(Gt)
/// 1
/// ```
///
pub fn to_int(order: Order) -> Int {
case order {
Lt -> -1
Eq -> 0
Gt -> 1
}
}
/// Compares two `Order` values to one another, producing a new `Order`.
///
/// ## Examples
///
/// ```gleam
/// > compare(Eq, with: Lt)
/// Gt
/// ```
///
pub fn compare(a: Order, with b: Order) -> Order {
case a, b {
x, y if x == y -> Eq
Lt, _ | Eq, Gt -> Lt
_, _ -> Gt
}
}
/// Returns the largest of two orders given that `Gt > Eq > Lt`.
///
/// ## Examples
///
/// ```gleam
/// > max(Eq, Lt)
/// Eq
/// ```
///
pub fn max(a: Order, b: Order) -> Order {
case a, b {
Gt, _ -> Gt
Eq, Lt -> Eq
_, _ -> b
}
}
/// Returns the smallest of two orders given that `Gt > Eq > Lt`.
///
/// ## Examples
///
/// ```gleam
/// > min(Eq, Lt)
/// Lt
/// ```
///
pub fn min(a: Order, b: Order) -> Order {
case a, b {
Lt, _ -> Lt
Eq, Gt -> Eq
_, _ -> b
}
}
/// Inverts an ordering function, so less-than becomes greater-than and greater-than
/// becomes less-than.
///
/// ## Examples
///
/// ```gleam
/// > list.sort([1, 5, 4], by: reverse(int.compare))
/// [5, 4, 1]
/// ```
///
pub fn reverse(orderer: fn(a, a) -> Order) -> fn(a, a) -> Order {
fn(a, b) { orderer(b, a) }
}