forked from baetheus/fun
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsemigroup.ts
More file actions
394 lines (379 loc) · 10.3 KB
/
semigroup.ts
File metadata and controls
394 lines (379 loc) · 10.3 KB
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
/**
* Semigroup is an algebra over associativity and totality. It's
* basic purpose can be understood as "a way to merge, concatenate,
* or combine" two of a thing into one thing.
*
* This file contains the Semigroup algebra, a collection of
* instance getters, and some utilities around Semigroups.
*
* @module Semigroup
*/
import type { ReadonlyRecord } from "./record.ts";
import type { Ord } from "./ord.ts";
import * as O from "./ord.ts";
import { reduce } from "./array.ts";
import { pipe } from "./fn.ts";
/**
* A Semigroup<T> is an algebra with a notion of concatenation. This
* means that it's used to merge two Ts into one T. The only rule
* that this merging must follow is that if you merge A, B, and C,
* that it doesn't matter if you start by merging A and B or start
* by merging B and C. There are many ways to merge values that
* follow these rules. A simple example is addition for numbers.
* It doesn't matter if you add (A + B) + C or if you add A + (B + C).
* The resulting sum will be the same. Thus, (number, +) can be
* used to make a Semigroup<number> (see [SemigroupNumberSum](./number.ts)
* for this exact instance).
*
* An instance of concat must obey the following laws:
*
* 1. Associativity:
* pipe(a, concat(b), concat(c)) === pipe(a, concat(pipe(b, concat(c))))
*
* The original type came from
* [static-land](https://github.com/fantasyland/static-land/blob/master/docs/spec.md#semigroup)
*
* @since 2.0.0
*/
export interface Semigroup<D> {
readonly concat: (right: D) => (left: D) => D;
}
/**
* A type for Semigroup over any, useful as an extension target for
* functions that take any Semigroup and do not need to
* extract the type.
*
* @since 2.0.0
*/
// deno-lint-ignore no-explicit-any
export type AnySemigroup = Semigroup<any>;
/**
* A type level extractor, used to pull the inner type from a Semigroup.
*
* @since 2.0.0
*/
export type TypeOf<T> = T extends Semigroup<infer A> ? A : never;
/**
* Get an Semigroup over A that always returns the first
* parameter supplied to concat (confusingly this is
* actually the last parameter since concat is in curried
* form).
*
* @example
* ```ts
* import { first } from "./semigroup.ts";
* import { pipe } from "./fn.ts";
*
* type Person = { name: string, age: number };
*
* const SemigroupPerson = first<Person>();
*
* const octavia: Person = { name: "Octavia", age: 42 };
* const kimbra: Person = { name: "Kimbra", age: 32 };
* const brandon: Person = { name: "Brandon", age: 37 };
*
* const firstPerson = pipe(
* octavia,
* SemigroupPerson.concat(kimbra),
* SemigroupPerson.concat(brandon),
* ); // firstPerson === octavia
* ```
*
* @since 2.0.0
*/
export function first<A = never>(): Semigroup<A> {
return ({ concat: () => (left) => left });
}
/**
* Get an Semigroup over A that always returns the last
* parameter supplied to concat (confusingly this is
* actually the first parameter since concat is in curried
* form).
*
* @example
* ```ts
* import { last } from "./semigroup.ts";
* import { pipe } from "./fn.ts";
*
* type Person = { name: string, age: number };
*
* const SemigroupPerson = last<Person>();
*
* const octavia: Person = { name: "Octavia", age: 42 };
* const kimbra: Person = { name: "Kimbra", age: 32 };
* const brandon: Person = { name: "Brandon", age: 37 };
*
* const lastPerson = pipe(
* octavia,
* SemigroupPerson.concat(kimbra),
* SemigroupPerson.concat(brandon),
* ); // lastPerson === brandon
* ```
*
* @since 2.0.0
*/
export function last<A = never>(): Semigroup<A> {
return ({ concat: (right) => () => right });
}
/**
* Get the "Dual" of an existing Semigroup. This effectively reverses
* the order of the input semigroup's application. For example, the
* dual of the "first" semigroup is the "last" semigroup. The dual
* of (boolean, ||) is itself.
*
* @example
* ```ts
* import * as SG from "./semigroup.ts";
* import { pipe } from "./fn.ts";
*
* type Person = { name: string, age: number };
*
* const last = SG.last<Person>();
* const dual = SG.dual(last);
*
* const octavia: Person = { name: "Octavia", age: 42 };
* const kimbra: Person = { name: "Kimbra", age: 32 };
* const brandon: Person = { name: "Brandon", age: 37 };
*
* const dualPerson = pipe(
* octavia,
* dual.concat(kimbra),
* dual.concat(brandon),
* ); // dualPerson === octavia
* ```
*
* @since 2.0.0
*/
export function dual<A>(S: Semigroup<A>): Semigroup<A> {
return ({ concat: (right) => (left) => S.concat(left)(right) });
}
/**
* Get a Semigroup from a tuple of semigroups. The resulting
* semigroup will operate over tuples applying the input
* semigroups applying each based on its position,
*
* @example
* ```ts
* import * as SG from "./semigroup.ts";
* import { pipe } from "./fn.ts";
*
* type Person = { name: string, age: number };
*
* const first = SG.first<Person>();
* const last = SG.last<Person>();
* const { concat } = SG.tuple(first, last);
*
* const octavia: Person = { name: "Octavia", age: 42 };
* const kimbra: Person = { name: "Kimbra", age: 32 };
* const brandon: Person = { name: "Brandon", age: 37 };
*
* const tuplePeople = pipe(
* [octavia, octavia],
* concat([kimbra, kimbra]),
* concat([brandon, brandon]),
* ); // tuplePeople === [octavia, brandon]
* ```
*
* @since 2.0.0
*/
export function tuple<T extends AnySemigroup[]>(
...semigroups: T
): Semigroup<{ readonly [K in keyof T]: TypeOf<T[K]> }> {
type Return = { [K in keyof T]: TypeOf<T[K]> };
return ({
concat: (right) => (left): Return =>
semigroups.map((s, i) =>
s.concat(right[i])(left[i])
) as unknown as Return,
});
}
/**
* Get a Semigroup from a struct of semigroups. The resulting
* semigroup will operate over similar shaped structs applying
* the input semigroups applying each based on its position,
*
* @example
* ```ts
* import type { Semigroup } from "./semigroup.ts";
* import * as SG from "./semigroup.ts";
* import * as N from "./number.ts";
* import { pipe } from "./fn.ts";
*
* type Person = { name: string, age: number };
* const person = (name: string, age: number): Person => ({ name, age });
*
* // Chooses the longest string, defaulting to left when equal
* const longestString: Semigroup<string> = {
* concat: (right) => (left) => right.length > left.length ? right : left,
* };
*
* // This semigroup will merge two people, choosing the longest
* // name and the oldest age
* const { concat } = SG.struct<Person>({
* name: longestString,
* age: N.SemigroupNumberMax,
* })
*
* const brandon = pipe(
* person("Brandon Blaylock", 12),
* concat(person("Bdon", 17)),
* concat(person("Brandon", 30))
* ); // brandon === { name: "Brandon Blaylock", age: 30 }
* ```
*
* @since 2.0.0
*/
// deno-lint-ignore no-explicit-any
export function struct<O extends ReadonlyRecord<any>>(
semigroups: { [K in keyof O]: Semigroup<O[K]> },
): Semigroup<O> {
type Entries = [keyof O, typeof semigroups[keyof O]][];
return ({
concat: (right) => (left) => {
const r = {} as Record<keyof O, O[keyof O]>;
for (const [key, semigroup] of Object.entries(semigroups) as Entries) {
r[key] = semigroup.concat(right[key])(left[key]);
}
return r as { [K in keyof O]: O[K] };
},
});
}
/**
* Create a semigroup fron an instance of Ord that returns
* that maximum for the type being ordered. This Semigroup
* functions identically to max from Ord.
*
* @example
* ```ts
* import * as SG from "./semigroup.ts";
* import * as N from "./number.ts";
* import { pipe } from "./fn.ts";
*
* const { concat } = SG.max(N.OrdNumber);
*
* const biggest = pipe(
* 0,
* concat(-1),
* concat(10),
* concat(1000),
* concat(5),
* concat(9001)
* ); // biggest is over 9000
* ```
*
* @since 2.0.0
*/
export function max<A>(ord: Ord<A>): Semigroup<A> {
return { concat: O.max(ord) };
}
/**
* Create a semigroup fron an instance of Ord that returns
* that minimum for the type being ordered. This Semigroup
* functions identically to min from Ord.
*
* @example
* ```ts
* import * as SG from "./semigroup.ts";
* import * as N from "./number.ts";
* import { pipe } from "./fn.ts";
*
* const { concat } = SG.min(N.OrdNumber);
*
* const smallest = pipe(
* 0,
* concat(-1),
* concat(10),
* concat(1000),
* concat(5),
* concat(9001)
* ); // smallest is -1
* ```
*
* @since 2.0.0
*/
export function min<A>(ord: Ord<A>): Semigroup<A> {
return { concat: O.min(ord) };
}
/**
* Create a semigroup that works like Array.join,
* inserting middle between every two values
* that are concatenated. This can have some interesting
* results.
*
* @example
* ```ts
* import * as SG from "./semigroup.ts";
* import * as S from "./string.ts";
* import { pipe } from "./fn.ts";
*
* const { concat: toList } = pipe(
* S.SemigroupString,
* SG.intercalcate(", "),
* );
*
* const list = pipe(
* "apples",
* toList("oranges"),
* toList("and bananas"),
* ); // list === "apples, oranges, and bananas"
* ```
*
* @since 2.0.0
*/
export function intercalcate<A>(middle: A) {
return (S: Semigroup<A>): Semigroup<A> => ({
concat: (right) => S.concat(pipe(middle, S.concat(right))),
});
}
/**
* Create a semigroup that always returns the
* given value, ignoring anything that it is
* concatenated with.
*
* @example
* ```ts
* import * as SG from "./semigroup.ts";
* import { pipe } from "./fn.ts";
*
* const { concat } = SG.constant("cake");
*
* const whatDoWeWant = pipe(
* "apples",
* concat("oranges"),
* concat("bananas"),
* concat("pie"),
* concat("money"),
* ); // whatDoWeWant === "cake"
* ```
*
* @since 2.0.0
*/
export function constant<A>(a: A): Semigroup<A> {
return { concat: () => () => a };
}
/**
* Given a semigroup, create a function that will
* iterate through an array of values and concat
* them. This is not much more than Array.reduce(concat).
*
* @example
* ```ts
* import * as SG from "./semigroup.ts";
* import * as N from "./number.ts";
* import { pipe } from "./fn.ts";
*
* const sumAll = SG.concatAll(N.SemigroupNumberSum);
*
* const sum = pipe(
* [1, 30, 80, 1000, 52, 42],
* sumAll(0),
* ); // sum === 1205
* ```
*
* @since 2.0.0
*/
export function concatAll<A>(
S: Semigroup<A>,
): (startWith: A) => (as: ReadonlyArray<A>) => A {
return (startWith) => reduce((a, c) => S.concat(c)(a), startWith);
}