-
Notifications
You must be signed in to change notification settings - Fork 7
/
fn_either.ts
753 lines (714 loc) · 17.4 KB
/
fn_either.ts
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
/**
* FnEither is also known as ReaderEither. In essence a FnEither is
* a function that returns an either. This pattern can be used as
* a validation, a failable computation, a computation resulting
* in a "Choice", and many other things.
*
* @module FnEither
*/
import type { In, Kind, Out } from "./kind.ts";
import type { Applicable } from "./applicable.ts";
import type { Bimappable } from "./bimappable.ts";
import type { Combinable } from "./combinable.ts";
import type { Composable } from "./composable.ts";
import type { Either } from "./either.ts";
import type { Failable, Tap } from "./failable.ts";
import type { Bind, Flatmappable } from "./flatmappable.ts";
import type { Fn } from "./fn.ts";
import type { BindTo, Mappable } from "./mappable.ts";
import type { Predicate } from "./predicate.ts";
import type { Premappable } from "./premappable.ts";
import type { Refinement } from "./refinement.ts";
import type { Wrappable } from "./wrappable.ts";
import * as E from "./either.ts";
import * as F from "./fn.ts";
import { createTap } from "./failable.ts";
import { createBind } from "./flatmappable.ts";
import { createBindTo } from "./mappable.ts";
/**
* A FnEither, also known as ReaderEither, is a type over a variadic
* javascript function that returns an Either.
* ie. (a: number, b: string) => Either<Error, string> can be
* a FnEither. As an algebraic data type, the associated type class
* instances for Fn are limited to single variable inputs so they will
* look like (a: number) => Either<Error, string>, with only one
* argument. The purposes of a FnEither are many and varied, some
* common purposes are: failable computation, reading values from a
* shared environment, and sub-computations in a modified
* environment.
*
* Currently, there is no implementation of Chain recursion or
* trampolining for FnEIther implemented, but it is likely to be a future
* feature. Once implemented Fn will gain some much needed stack safety.
*
* @since 2.0.0
*/
export type FnEither<D, B, A> = Fn<D, Either<B, A>>;
/**
* A FnEither type over any, useful for constraining generics that
* take or return FnEithers.
*
* @since 2.0.0
*/
// deno-lint-ignore no-explicit-any
export type AnyFnEither = FnEither<any, any, any>;
/**
* Specifies FnEither as a Higher Kinded Type, with
* covariant parameter A and B corresponding to the 0th
* and 1st indices of any Substitutions and a contravariant
* parameter D corresponding to the 0th index of
* any Substititions. The FnEither KindFnEither is unique in that
* it constrains the FnEither type to taking a single
* argument for the purposes of type substitution
* while the implementations of FnEither combinators such
* as map, flatmap, etc are mostly variadic (multiple
* arguments).
*
* @since 2.0.0
*/
export interface KindFnEither extends Kind {
readonly kind: FnEither<In<this, 0>, Out<this, 1>, Out<this, 0>>;
}
/**
* Specifies FnEither as a Higher Kinded Type, with
* covariant parameter A corresponding to the 0th
* index of any Substitutions and a contravariant
* parameter D corresponding to the 0th index of
* any Substititions. KindRightFnEither curries the Left parameter
* of the output Either. This is useful when one
* needs to Fix the Left output with a Combinable or
* some other collection algebraic structure.
*
* @since 2.0.0
*/
export interface KindRightFnEither<B> extends Kind {
readonly kind: FnEither<In<this, 0>, B, Out<this, 0>>;
}
/**
* Wrap any function in a try catch block. The returned
* function will lazily call and handle any throwing of
* the wrapped function. Non-throwing calls will be
* returned in a Right, and throwing calls will have
* their error and arguments passed to the onThrow function
* before being returned in a Left.
*
* @example
* ```ts
* import { tryCatch } from "./fn_either.ts";
* import { todo } from "./fn.ts";
*
* const throws = tryCatch(todo<number>, () => "Failed!");
* const returns = tryCatch((n: number) => n, () => "Failed!");
*
* const result1 = throws()(0); // Left("Failed!");
* const result2 = returns(1)(0); // Right(1);
* ```
*
* @since 2.0.0
*/
export function tryCatch<D extends unknown[], B, A>(
ua: (...d: D) => A,
onThrow: (e: unknown, d: D) => B,
): (...d: D) => FnEither<unknown, B, A> {
return F.handleThrow(
ua,
right,
(e, d) => left(onThrow(e, d)),
);
}
/**
* Create a FnEither that always returns a Left(B).
*
* @example
* ```ts
* import { left } from "./fn_either.ts";
*
* const leftNumber = left(1);
*
* const result = leftNumber(0); // Left(1);
* ```
*
* @since 2.0.0
*/
export function left<B, D = unknown, A = never>(
left: B,
): FnEither<D, B, A> {
return F.wrap(E.left(left));
}
/**
* Create a FnEither that always returns a Right(A).
*
* @example
* ```ts
* import { right } from "./fn_either.ts";
*
* const rightNumber = right(1);
*
* const result = rightNumber(null); // Right(1);
* ```
*
* @since 2.0.0
*/
export function right<A, D = unknown, B = never>(
right: A,
): FnEither<D, B, A> {
return F.wrap(E.right(right));
}
/**
* Turn an Either into a FnEither.
*
* @example
* ```ts
* import * as FE from "./fn_either.ts";
* import * as E from "./either.ts";
*
* const left = E.left(1);
* const right = E.right(1);
*
* const fnLeft = FE.fromEither(left);
* const fnRight = FE.fromEither(right);
*
* const result1 = fnLeft(null); // Left(1);
* const result2 = fnRight(null); // Right(1);
* ```
*
* @since 2.0.0
*/
export function fromEither<A, B, D = unknown>(
ua: Either<B, A>,
): FnEither<D, B, A> {
return F.wrap(ua);
}
/**
* Lift a Fn<D, A> into FnEither<[D], never, A>
*
* @example
* ```ts
* import { fromFn } from "./fn_either.ts";
*
* const double = (first: number) => first + first;
* const lifted = fromFn(double);
*
* const result = lifted(1); // Right(2)
* ```
*
* @since 2.0.0
*/
export function fromFn<D, A>(
fda: Fn<D, A>,
): FnEither<D, never, A> {
return F.flow(fda, E.right);
}
/**
* Create a FnEither from a Predicate or a Refinement.
* If the Predicate or Refinement returns true then the
* FnEither returns Right, otherwise it returns Left.
*
* @example
* ```ts
* import * as FE from "./fn_either.ts";
* import { pipe } from "./fn.ts";
*
* const isPositive = (n: number) => n > 0;
* const computation = FE.fromPredicate(isPositive);
*
* const result1 = computation(0); // Left(0)
* const result2 = computation(1); // Right(1)
* ```
*
* @since 2.0.0
*/
export function fromPredicate<A, B extends A>(
refinement: Refinement<A, B>,
): FnEither<A, A, B>;
export function fromPredicate<A>(
predicate: Predicate<A>,
): FnEither<A, A, A>;
export function fromPredicate<A>(
predicate: Predicate<A>,
): FnEither<A, A, A> {
return (a) => predicate(a) ? E.right(a) : E.left(a);
}
/**
* An alias for right. Creates a FnEither from a value. The created
* FnEither does not require any arguments, but can widen when used
* in a flatmap.
*
* @example
* ```ts
* import * as FE from "./fn_either.ts";
* import { pipe } from "./fn.ts";
*
* const computation = pipe(
* FE.id<number>(), // Ask for a number
* FE.map(n => n + 1), // Add one
* FE.flatmap(_ => FE.wrap("Hello")), // Forget about the number
* );
*
* const result = computation(1); // Right("Hello")
* ```
*
* @since 2.0.0
*/
export function wrap<A, D = unknown, B = never>(
a: A,
): FnEither<D, B, A> {
return right(a);
}
/**
* @since 2.0.0
*/
export function fail<A = never, B = never, D = unknown>(
b: B,
): FnEither<D, B, A> {
return left(b);
}
/**
* Given a FnEither returning a function A => I and a FnEither returning
* a value A, combine them into a FnEither returning an I.
*
* @example
* ```ts
* import * as FE from "./fn_either.ts";
* import { pipe } from "./fn.ts";
*
* type Person = { name: string; age: number };
*
* const person = (name: string) => (age: number): Person => ({ name, age });
*
* const result = pipe(
* FE.wrap(person),
* FE.apply(FE.wrap("Brandon")),
* FE.apply(FE.wrap(37)),
* ); // FnEither<[], never, Person>
* ```
*
* @since 2.0.0
*/
export function apply<D, B, A>(
ua: FnEither<D, B, A>,
): <L, I, J>(ufai: FnEither<L, J, (a: A) => I>) => FnEither<D & L, B | J, I> {
return (ufai) => (d) => F.pipe(ufai(d), E.apply(ua(d)));
}
/**
* Provide an alternative FnEither in the event that an original
* FnEither returns Left.
*
* @example
* ```ts
* import * as FE from "./fn_either.ts";
* import { pipe } from "./fn.ts";
*
* const result = pipe(
* FE.left("Oh no I broke!"),
* FE.alt(FE.right("But I work")),
* )(null); // Right("But I work")
* ```
*
* @since 2.0.0
*/
export function alt<A, B, D>(
ub: FnEither<D, B, A>,
): (ua: FnEither<D, B, A>) => FnEither<D, B, A> {
return (ua) => (d) => {
const e = ua(d);
return E.isLeft(e) ? ub(d) : e;
};
}
/**
* Map over the left and right return values of a FnEither.
*
* @example
* ```ts
* import * as FE from "./fn_either.ts";
* import * as E from "./either.ts";
* import { pipe } from "./fn.ts";
*
* const boundedValue = (n: number) => n > 10 || n < 0 ? E.left(n) : E.right(n);
*
* const log = pipe(
* boundedValue,
* FE.bimap(n => `Out of bounds: ${n}`, n => `Received a good value: ${n}`),
* );
*
* const result1 = log(1); // Right("Received a good value: 1")
* const result2 = log(20); // Left("Out of bounds: 20")
* ```
*
* @since 2.0.0
*/
export function bimap<A, I, B, J>(
fbj: (b: B) => J,
fai: (a: A) => I,
): <D = unknown>(
ua: FnEither<D, B, A>,
) => FnEither<D, J, I> {
return F.map(E.bimap(fbj, fai));
}
/**
* Map over the right return value of a FnEither.
*
* @example
* ```ts
* import * as FE from "./fn_either.ts";
* import { pipe } from "./fn.ts";
*
* const result = pipe(
* FE.id<number>(),
* FE.map(n => n + 1),
* )(0); // Right(1)
* ```
*
* @since 2.0.0
*/
export function map<A, I>(
fai: (a: A) => I,
): <B = never, D = unknown>(
ua: FnEither<D, B, A>,
) => FnEither<D, B, I> {
return F.map(E.map(fai));
}
/**
* Map over the left return value of a FnEither.
*
* @example
* ```ts
* import * as FE from "./fn_either.ts";
* import { pipe } from "./fn.ts";
*
* const result1 = pipe(
* FE.id<number>(),
* FE.mapSecond((n: number) => n + 1),
* )(0); // Right(0)
*
* const result2 = pipe(
* FE.idLeft<number>(),
* FE.mapSecond(n => n + 1),
* )(0); // Left(1)
* ```
*
* @since 2.0.0
*/
export function mapSecond<B, J>(
fbj: (b: B) => J,
): <A = never, D = unknown>(
ua: FnEither<D, B, A>,
) => FnEither<D, J, A> {
return F.map(E.mapSecond(fbj));
}
/**
* Flatten nested FnEithers with the same input and
* left types.
*
* @example
* ```ts
* import * as FE from "./fn_either.ts";
* import { pipe } from "./fn.ts";
*
* const result = pipe(
* FE.right(FE.right(1)),
* FE.join,
* )(null); // Right(1)
* ```
*
* @since 2.0.0
*/
export function join<D, A, B, L, J>(
tua: FnEither<L, J, FnEither<D, B, A>>,
): FnEither<D & L, B | J, A> {
return (d) => F.pipe(tua(d), E.flatmap((fn) => fn(d)));
}
/**
* Chain the right result of one FnEither into another
* FnEither.
*
* @example
* ```ts
* import * as FE from "./fn_either.ts";
* import { pipe } from "./fn.ts";
*
* const result = pipe(
* FE.id<string>(),
* FE.flatmap(s => FE.right(s.length)),
* )("Hello"); // Right(5)
* ```
*
* @since 2.0.0
*/
export function flatmap<A, L = unknown, J = never, I = never>(
fati: (a: A) => FnEither<L, J, I>,
): <D = unknown, B = never>(
ua: FnEither<D, B, A>,
) => FnEither<D & L, B | J, I> {
return (ua) => (d) => {
const e = ua(d);
return E.isLeft(e) ? e : fati(e.right)(d);
};
}
/**
* Chain the left result of one FnEither into another
* FnEither.
*
* @example
* ```ts
* import * as FE from "./fn_either.ts";
* import { pipe } from "./fn.ts";
*
* const result = pipe(
* FE.id<string, number>(),
* FE.flatmap(s => FE.left(s.length)),
* FE.recover(n => FE.right(String(n))),
* )("Hello"); // Right("5")
* ```
*
* @since 2.0.0
*/
export function recover<B, D = unknown, I = never, J = never>(
fbtj: (b: B) => FnEither<D, J, I>,
): <A = never>(
ua: FnEither<D, B, A>,
) => FnEither<D, J, A | I> {
return (ua) => (d) => {
const e = ua(d);
return E.isRight(e) ? e : fbtj(e.left)(d);
};
}
/**
* Map over the input value of a FnEither.
*
* @example
* ```ts
* import * as FE from "./fn_either.ts";
* import { pipe } from "./fn.ts";
*
* // This has type FnEither<[Date], never, number>
* const computation = pipe(
* FE.id<number>(),
* FE.premap((d: Date) => d.valueOf()),
* );
*
* const result = computation(new Date(0)); // Right(0)
* ```
*
* @since 2.0.0
*/
export function premap<L, D>(
fld: (l: L) => D,
): <A, B>(ua: FnEither<D, B, A>) => FnEither<L, B, A> {
return (ua) => F.flow(fld, ua);
}
/**
* Map over the input of a FnEither contravariantly and the
* right result of a FnEither covariantly.
*
* @example
* ```ts
* import * as FE from "./fn_either.ts";
* import { pipe } from "./fn.ts";
*
* // This has type FnEither<[Date], never, string>
* const computation = pipe(
* FE.id<number>(),
* FE.dimap(
* (d: Date) => d.valueOf(),
* String,
* ),
* );
*
* const result = computation(new Date(0)); // Right('0')
* ```
*
* @since 2.0.0
*/
export function dimap<A, I, L, D>(
fld: (l: L) => D,
fai: (a: A) => I,
): <B>(ua: FnEither<D, B, A>) => FnEither<L, B, I> {
return F.flow(premap(fld), map(fai));
}
/**
* Perform the same function as Reader ask. Given a type A
* (and optionally a type B), return a FnEither<[A], B, A>.
* This is useful for starting a FnEither flatmap.
*
* @example
* ```ts
* import * as FE from "./fn_either.ts";
* import { pipe } from "./fn.ts";
*
* const computation = FE.id<number>();
*
* const result1 = computation(1); // Right(1);
* const result2 = computation(2); // Right(2);
* ```
*
* @since 2.0.0
*/
export function id<A, B = never>(): FnEither<A, B, A> {
return E.right;
}
/**
* Perform the same function as Reader askLeft. Given a type B
* (and optionally a type A), return a FnEither<[B], B, A>.
* This is useful for starting a FnEither flatmap with a left value.
*
* @example
* ```ts
* import * as FE from "./fn_either.ts";
* import { pipe } from "./fn.ts";
*
* const computation = FE.idLeft<number>();
*
* const result1 = computation(1); // Left(1);
* const result2 = computation(2); // Left(2);
* ```
*
* @since 2.0.0
*/
export function idLeft<B, A = never>(): FnEither<B, B, A> {
return E.left;
}
/**
* Compose two FnEithers, passing the right value of the first
* into the second.
*
* @example
* ```ts
* import * as FE from "./fn_either.ts";
* import { pipe } from "./fn.ts";
*
* const isPositive = (n: number) => n > 0;
* const isInteger = (n: number) => Number.isInteger(n);
*
* const isPositiveInteger = pipe(
* FE.fromPredicate(isPositive),
* FE.compose(FE.fromPredicate(isInteger)),
* );
*
* const result1 = isPositiveInteger(0); // Left(0)
* const result2 = isPositiveInteger(1); // Right(1)
* const result3 = isPositiveInteger(1.1); // Left(1.1)
* ```
*
* @since 2.0.0
*/
export function compose<A, I, J>(
second: FnEither<A, J, I>,
): <B, D>(
first: FnEither<D, B, A>,
) => FnEither<D, B | J, I> {
return (first) => F.flow(first, E.flatmap(second));
}
/**
* Create a Flatmappable for FnEither where left values are combined using the
* supplied Combinable.
*
* @example
* ```ts
* import * as FE from "./fn_either.ts";
* import { InitializableNumberSum } from "./number.ts";
* import { pipe } from "./fn.ts";
*
* const { apply } = FE.getRightFlatmappable(InitializableNumberSum);
*
* const result1 = pipe(
* FE.left(1),
* apply(FE.left(1)),
* ); // Left(2)
* ```
*
* @since 2.0.0
*/
export function getRightFlatmappable<B>(
{ combine }: Combinable<B>,
): Flatmappable<KindRightFnEither<B>> {
return ({
wrap,
apply: (ua) => (ufai) => (c) => {
const efai = ufai(c);
const ea = ua(c);
return E.isLeft(efai)
? (E.isLeft(ea) ? E.left(combine(efai.left)(ea.left)) : efai)
: (E.isLeft(ea) ? ea : E.right(efai.right(ea.right)));
},
map,
flatmap,
});
}
/**
* @since 2.0.0
*/
export const ApplicableFnEither: Applicable<KindFnEither> = {
apply,
map,
wrap,
};
/**
* The canonical implementation of Bimappable for FnEither. It contains
* the methods bimap and mapSecond.
*
* @since 2.0.0
*/
export const BimappableFnEither: Bimappable<KindFnEither> = {
map,
mapSecond,
};
/**
* @since 2.0.0
*/
export const ComposableFnEither: Composable<KindFnEither> = { compose, id };
/**
* The canonical implementation of Flatmappable for FnEither. It contains
* the methods wrap, apply, map, and flatmap.
*
* @since 2.0.0
*/
export const FlatmappableFnEither: Flatmappable<KindFnEither> = {
wrap,
apply,
map,
flatmap,
};
/**
* @since 2.0.0
*/
export const FailableFnEither: Failable<KindFnEither> = {
apply,
flatmap,
map,
wrap,
fail,
alt,
recover,
};
/**
* @since 2.0.0
*/
export const MappableFnEither: Mappable<KindFnEither> = { map };
/**
* The canonical implementation of Premappable for FnEither. It contains
* the method premap.
*
* @since 2.0.0
*/
export const PremappableFnEither: Premappable<KindFnEither> = {
premap,
map,
dimap,
};
/**
* @since 2.0.0
*/
export const WrappableFnEither: Wrappable<KindFnEither> = { wrap };
/**
* @since 2.0.0
*/
export const tap: Tap<KindFnEither> = createTap(FailableFnEither);
/**
* @since 2.0.0
*/
export const bind: Bind<KindFnEither> = createBind(FlatmappableFnEither);
/**
* @since 2.0.0
*/
export const bindTo: BindTo<KindFnEither> = createBindTo(MappableFnEither);