-
-
Notifications
You must be signed in to change notification settings - Fork 95
/
index.js
3526 lines (3308 loc) · 97.6 KB
/
index.js
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
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* #######
#### ####
#### ### ####
##### ########### sanctuary
######## ######## noun
########### ##### 1 [ mass noun ] refuge from unsafe JavaScript
#### ### ####
#### ####
####### */
//. # Sanctuary
//.
//. Sanctuary is a functional programming library inspired by Haskell and
//. PureScript. It depends on and works nicely with [Ramda][]. Sanctuary
//. makes it possible to write safe code without null checks.
//.
//. In JavaScript it's trivial to introduce a possible run-time type error:
//.
//. words[0].toUpperCase()
//.
//. If `words` is `[]` we'll get a familiar error at run-time:
//.
//. TypeError: Cannot read property 'toUpperCase' of undefined
//.
//. Sanctuary gives us a fighting chance of avoiding such errors. We might
//. write:
//.
//. R.map(S.toUpper, S.head(words))
//.
//. Sanctuary is designed to work in Node.js and in ES5-compatible browsers.
//.
//. ## Types
//.
//. Sanctuary uses Haskell-like type signatures to describe the types of
//. values, including functions. `'foo'`, for example, has type `String`;
//. `[1, 2, 3]` has type `Array Number`. The arrow (`->`) is used to express
//. a function's type. `Math.abs`, for example, has type `Number -> Number`.
//. That is, it takes an argument of type `Number` and returns a value of
//. type `Number`.
//.
//. [`R.map`][R.map] has type `(a -> b) -> Array a -> Array b`. That is,
//. it takes an argument of type `a -> b` and returns a value of type
//. `Array a -> Array b`. `a` and `b` are type variables: applying `R.map`
//. to a value of type `String -> Number` will result in a value of type
//. `Array String -> Array Number`.
//.
//. Sanctuary embraces types. JavaScript doesn't support algebraic data types,
//. but these can be simulated by providing a group of data constructors which
//. return values with the same set of methods. A value of the Maybe type, for
//. example, is created via the Nothing constructor or the Just constructor.
//.
//. It's necessary to extend Haskell's notation to describe implicit arguments
//. to the *methods* provided by Sanctuary's types. In `x.map(y)`, for example,
//. the `map` method takes an implicit argument `x` in addition to the explicit
//. argument `y`. The type of the value upon which a method is invoked appears
//. at the beginning of the signature, separated from the arguments and return
//. value by a squiggly arrow (`~>`). The type of the `map` method of the Maybe
//. type is written `Maybe a ~> (a -> b) -> Maybe b`. One could read this as:
//.
//. _When the `map` method is invoked on a value of type `Maybe a`
//. (for any type `a`) with an argument of type `a -> b` (for any type `b`),
//. it returns a value of type `Maybe b`._
//.
//. Sanctuary supports type classes: constraints on type variables. Whereas
//. `a -> a` implicitly supports every type, `Functor f => (a -> b) -> f a ->
//. f b` requires that `f` be a type which satisfies the requirements of the
//. Functor type class. Type-class constraints appear at the beginning of a
//. type signature, separated from the rest of the signature by a fat arrow
//. (`=>`).
//.
//. ### Accessible pseudotype
//.
//. What is the type of values which support property access? In other words,
//. what is the type of which every value except `null` and `undefined` is a
//. member? Object is close, but `Object.create(null)` produces a value which
//. supports property access but which is not a member of the Object type.
//.
//. Sanctuary uses the Accessible pseudotype to represent the set of values
//. which support property access.
//.
//. ### Integer pseudotype
//.
//. The Integer pseudotype represents integers in the range (-2^53 .. 2^53).
//. It is a pseudotype because each Integer is represented by a Number value.
//. Sanctuary's run-time type checking asserts that a valid Number value is
//. provided wherever an Integer value is required.
//.
//. ### Type representatives
//.
//. What is the type of `Number`? One answer is `a -> Number`, since it's a
//. function which takes an argument of any type and returns a Number value.
//. When provided as the first argument to [`is`](#is), though, `Number` is
//. really the value-level representative of the Number type.
//.
//. Sanctuary uses the TypeRep pseudotype to describe type representatives.
//. For example:
//.
//. Number :: TypeRep Number
//.
//. `Number` is the sole inhabitant of the TypeRep Number type.
//.
//. ## Type checking
//.
//. Sanctuary functions are defined via [sanctuary-def][] to provide run-time
//. type checking. This is tremendously useful during development: type errors
//. are reported immediately, avoiding circuitous stack traces (at best) and
//. silent failures due to type coercion (at worst). For example:
//.
//. ```javascript
//. S.inc('XXX');
//. // ! TypeError: Invalid value
//. //
//. // inc :: FiniteNumber -> FiniteNumber
//. // ^^^^^^^^^^^^
//. // 1
//. //
//. // 1) "XXX" :: String
//. //
//. // The value at position 1 is not a member of ‘FiniteNumber’.
//. ```
//.
//. Compare this to the behaviour of Ramda's unchecked equivalent:
//.
//. ```javascript
//. R.inc('XXX');
//. // => NaN
//. ```
//.
//. There is a performance cost to run-time type checking. One may wish to
//. disable type checking in certain contexts to avoid paying this cost.
//. [`create`](#create) facilitates the creation of a Sanctuary module which
//. does not perform type checking.
//.
//. In Node, one could use an environment variable to determine whether to
//. perform type checking:
//.
//. ```javascript
//. const {create, env} = require('sanctuary');
//.
//. const checkTypes = process.env.NODE_ENV !== 'production';
//. const S = create({checkTypes: checkTypes, env: env});
//. ```
//.
//. ## API
(function(f) {
'use strict';
/* istanbul ignore else */
if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = f(require('ramda'), require('sanctuary-def'));
} else if (typeof define === 'function' && define.amd != null) {
define(['ramda', 'sanctuary-def'], f);
} else {
self.sanctuary = f(self.R, self.sanctuaryDef);
}
}(function(R, $) {
'use strict';
var _ = R.__;
var sentinel = {};
// _type :: a -> String
var _type = function(x) {
return x != null && R.type(x['@@type']) === 'String' ? x['@@type']
: R.type(x);
};
// compose2 :: ((b -> c), (a -> b)) -> a -> c
var compose2 = function(f, g) {
return function(x) {
return f(g(x));
};
};
// compose3 :: ((b -> c), (a -> b), a) -> c
var compose3 = function(f, g, x) {
return f(g(x));
};
// filter :: (Monad m, Monoid m) => ((a -> Boolean), m a) -> m a
var filter = function(pred, m) {
return m.chain(function(x) {
return pred(x) ? m.of(x) : m.empty();
});
};
// hasMethod :: String -> Any -> Boolean
var hasMethod = function(name) {
return function(x) {
return x != null && typeof x[name] === 'function';
};
};
// inspect :: -> String
var inspect = /* istanbul ignore next */ function() {
return this.toString();
};
// negativeZero :: a -> Boolean
var negativeZero = R.either(R.equals(-0), R.equals(new Number(-0)));
// Accessible :: TypeClass
var Accessible = $.TypeClass(
'sanctuary/Accessible',
function(x) { return x != null; }
);
// Applicative :: TypeClass
var Applicative = $.TypeClass(
'sanctuary/Applicative',
function(x) {
return _type(x) === 'Array' ||
Apply._test(x) && (hasMethod('of')(x) ||
hasMethod('of')(x.constructor));
}
);
// Apply :: TypeClass
var Apply = $.TypeClass(
'sanctuary/Apply',
function(x) {
return R.contains(_type(x), ['Array', 'Function']) ||
Functor._test(x) && hasMethod('ap')(x);
}
);
// Foldable :: TypeClass
var Foldable = $.TypeClass(
'sanctuary/Foldable',
function(x) {
return _type(x) === 'Array' || hasMethod('reduce')(x);
}
);
// Functor :: TypeClass
var Functor = $.TypeClass(
'sanctuary/Functor',
function(x) {
return R.contains(_type(x), ['Array', 'Function']) ||
hasMethod('map')(x);
}
);
// Monoid :: TypeClass
var Monoid = $.TypeClass(
'sanctuary/Monoid',
function(x) {
return R.contains(_type(x), ['Array', 'Boolean', 'Object', 'String']) ||
hasMethod('empty')(x);
}
);
// Ord :: TypeClass
var Ord = $.TypeClass(
'sanctuary/Ord',
R.anyPass([$.String._test, $.ValidDate._test, $.ValidNumber._test])
);
// Semigroup :: TypeClass
var Semigroup = $.TypeClass(
'sanctuary/Semigroup',
hasMethod('concat')
);
var a = $.TypeVariable('a');
var b = $.TypeVariable('b');
var c = $.TypeVariable('c');
var d = $.TypeVariable('d');
var f = $.TypeVariable('f');
var l = $.TypeVariable('l');
var r = $.TypeVariable('r');
// $Either :: Type -> Type -> Type
var $Either = $.BinaryType(
'sanctuary/Either',
function(x) { return x != null && x['@@type'] === 'sanctuary/Either'; },
function(either) { return either.isLeft ? [either.value] : []; },
function(either) { return either.isRight ? [either.value] : []; }
);
// List :: Type -> Type
var List = $.UnaryType(
'sanctuary/List',
function(x) {
return x != null &&
R.type(x) !== 'Function' &&
$.Integer._test(x.length) &&
x.length >= 0;
},
function(list) {
return list.length > 0 && R.type(list) !== 'String' ? [list[0]] : [];
}
);
// $Maybe :: Type -> Type
var $Maybe = $.UnaryType(
'sanctuary/Maybe',
function(x) { return x != null && x['@@type'] === 'sanctuary/Maybe'; },
function(maybe) { return maybe.isJust ? [maybe.value] : []; }
);
// TypeRep :: Type
var TypeRep = $.NullaryType(
'sanctuary/TypeRep',
function(x) {
return R.type(x) === 'Function' ||
(x != null &&
R.type(x.name) === 'String' &&
R.type(x.test) === 'Function');
}
);
// defaultEnv :: Array Type
var defaultEnv = $.env.concat([
$.FiniteNumber,
$.NonZeroFiniteNumber,
$Either,
$.Integer,
$Maybe,
$.Pair,
$.RegexFlags,
TypeRep,
$.ValidDate,
$.ValidNumber
]);
// Options :: Type
var Options = $.RecordType({checkTypes: $.Boolean, env: $.Array($.Any)});
// createSanctuary :: Options -> Module
var createSanctuary = function createSanctuary(opts) {
/* eslint-disable indent */
var S = {EitherType: $Either, MaybeType: $Maybe};
//# create :: { checkTypes :: Boolean, env :: Array Type } -> Module
//.
//. Takes an options record and returns a Sanctuary module. `checkTypes`
//. specifies whether to enable type checking. The module's polymorphic
//. functions (such as [`I`](#I)) require each value associated with a
//. type variable to be a member of at least one type in the environment.
//.
//. A well-typed application of a Sanctuary function will produce the same
//. result regardless of whether type checking is enabled. If type checking
//. is enabled, a badly typed application will produce an exception with a
//. descriptive error message.
//.
//. The following snippet demonstrates defining a custom type and using
//. `create` to produce a Sanctuary module which is aware of that type:
//.
//. ```javascript
//. const {create, env} = require('sanctuary');
//. const $ = require('sanctuary-def');
//.
//. // identityTypeName :: String
//. const identityTypeName = 'my-package/Identity';
//.
//. // Identity :: a -> Identity a
//. const Identity = function Identity(x) {
//. return {
//. '@@type': identityTypeName,
//. map: f => Identity(f(x)),
//. chain: f => f(x),
//. // ...
//. value: x,
//. };
//. };
//.
//. // isIdentity :: a -> Boolean
//. const isIdentity = x => x != null && x['@@type'] === identityTypeName;
//.
//. // identityToArray :: Identity a -> Array a
//. const identityToArray = identity => [identity.value];
//.
//. // IdentityType :: Type
//. const IdentityType =
//. $.UnaryType(identityTypeName, isIdentity, identityToArray);
//.
//. const S = create({
//. checkTypes: process.env.NODE_ENV !== 'production',
//. env: env.concat([IdentityType]),
//. });
//. ```
//.
//. See also [`env`](#env).
S.create =
$.create({checkTypes: opts.checkTypes, env: defaultEnv})('create',
{},
[Options, $.Object],
createSanctuary);
//# env :: Array Type
//.
//. The default environment, which may be used as is or as the basis of a
//. custom environment in conjunction with [`create`](#create).
S.env = defaultEnv;
var def = $.create(opts);
// Note: Type checking of method arguments takes place once all arguments
// have been provided (whereas function arguments are checked as early as
// possible). This is not ideal, but provides two benefits:
//
// - accurate type signatures in error messages (though "->" appears in
// place of "~>"); and
//
// - intuitive ordering (`a.m(b, c)` is checked in a-b-c order rather
// than b-c-a order).
var method = function(name, constraints, types, _f) {
var f = def(name, constraints, types, _f);
return def(name,
constraints,
R.repeat($.Any, types.length - 1),
function() { return R.apply(f, R.prepend(this, arguments)); });
};
// prop :: Accessible a => String -> a -> b
var prop =
def('prop',
{a: [Accessible]},
[$.String, a, b],
function(key, obj) {
var boxed = Object(obj);
if (key in boxed) {
return boxed[key];
} else {
throw new TypeError('‘prop’ expected object to have a property ' +
'named ‘' + key + '’; ' +
R.toString(obj) + ' does not');
}
});
//. ### Classify
//# type :: a -> String
//.
//. Takes a value, `x`, of any type and returns its type identifier. If
//. `x` has a `'@@type'` property whose value is a string, `x['@@type']`
//. is the type identifier. Otherwise, the type identifier is the result
//. of applying [`R.type`][R.type] to `x`.
//.
//. `'@@type'` properties should use the form `'<package-name>/<type-name>'`,
//. where `<package-name>` is the name of the npm package in which the type
//. is defined.
//.
//. ```javascript
//. > S.type(S.Just(42))
//. 'sanctuary/Maybe'
//.
//. > S.type([1, 2, 3])
//. 'Array'
//. ```
S.type =
def('type',
{},
[$.Any, $.String],
_type);
//# is :: TypeRep a -> b -> Boolean
//.
//. Takes a [type representative](#type-representatives) and a value of
//. any type and returns `true` if the given value is of the specified
//. type; `false` otherwise. Subtyping is not respected.
//.
//. ```javascript
//. > S.is(Number, 42)
//. true
//.
//. > S.is(Object, 42)
//. false
//.
//. > S.is(String, 42)
//. false
//. ```
var is = S.is =
def('is',
{},
[TypeRep, $.Any, $.Boolean],
function(type, x) {
return x != null && (
R.type(type.prototype['@@type']) === 'String' ?
x['@@type'] === type.prototype['@@type'] :
R.type(x) === R.nth(1, R.match(/function (\w*)/, String(type)))
);
});
//. ### Combinator
//# I :: a -> a
//.
//. The I combinator. Returns its argument. Equivalent to Haskell's `id`
//. function.
//.
//. ```javascript
//. > S.I('foo')
//. 'foo'
//. ```
var I = S.I =
def('I',
{},
[a, a],
function(x) { return x; });
//# K :: a -> b -> a
//.
//. The K combinator. Takes two values and returns the first. Equivalent to
//. Haskell's `const` function.
//.
//. ```javascript
//. > S.K('foo', 'bar')
//. 'foo'
//.
//. > R.map(S.K(42), R.range(0, 5))
//. [42, 42, 42, 42, 42]
//. ```
S.K =
def('K',
{},
[a, b, a],
function(x, y) { return x; });
//# A :: (a -> b) -> a -> b
//.
//. The A combinator. Takes a function and a value, and returns the result
//. of applying the function to the value. Equivalent to Haskell's `($)`
//. function.
//.
//. ```javascript
//. > S.A(S.inc, 42)
//. 43
//.
//. > R.map(S.A(R.__, 100), [S.inc, Math.sqrt])
//. [101, 10]
//. ```
S.A =
def('A',
{},
[$.Function, a, b],
function(f, x) { return f(x); });
//# T :: a -> (a -> b) -> b
//.
//. The T ([thrush][]) combinator. Takes a value and a function, and returns
//. the result of applying the function to the value. Equivalent to Haskell's
//. `(&)` function.
//.
//. ```javascript
//. > S.T(42, S.inc)
//. 43
//.
//. > R.map(S.T(100), [S.inc, Math.sqrt])
//. [101, 10]
//. ```
S.T =
def('T',
{},
[a, $.Function, b],
function(x, f) { return f(x); });
//# C :: (a -> b -> c) -> b -> a -> c
//.
//. The C combinator. Takes a curried binary function and two values, and
//. returns the result of applying the function to the values in reverse.
//. Equivalent to Haskell's `flip` function.
//.
//. This function is very similar to [`flip`](#flip), except that its first
//. argument must be curried. This allows it to work with manually curried
//. functions.
//.
//. ```javascript
//. > S.C(S.concat, 'foo', 'bar')
//. 'barfoo'
//.
//. > R.filter(S.C(R.gt, 0), [-1, -2, 3, -4, 4, 2])
//. [3, 4, 2]
//. ```
S.C =
def('C',
{},
[$.Function, b, a, c],
function(f, x, y) { return f(y)(x); });
//# B :: (b -> c) -> (a -> b) -> a -> c
//.
//. The B combinator. Takes two functions and a value, and returns the
//. result of applying the first function to the result of applying the
//. second to the value. Equivalent to [`compose`](#compose) and Haskell's
//. `(.)` function.
//.
//. ```javascript
//. > S.B(Math.sqrt, S.inc, 99)
//. 10
//. ```
S.B =
def('B',
{},
[$.Function, $.Function, a, c],
compose3);
//# S :: (a -> b -> c) -> (a -> b) -> a -> c
//.
//. The S combinator. Takes a curried binary function, a unary function,
//. and a value, and returns the result of applying the binary function to:
//.
//. - the value; and
//. - the result of applying the unary function to the value.
//.
//. ```javascript
//. > S.S(S.add, Math.sqrt, 100)
//. 110
//. ```
S.S =
def('S',
{},
[$.Function, $.Function, a, c],
function(f, g, x) { return f(x)(g(x)); });
//. ### Function
//# flip :: ((a, b) -> c) -> b -> a -> c
//.
//. Takes a binary function and two values and returns the result of
//. applying the function - with its argument order reversed - to the
//. values. `flip` may also be applied to a Ramda-style curried
//. function with arity greater than two.
//.
//. See also [`C`](#C).
//.
//. ```javascript
//. > R.map(S.flip(Math.pow)(2), [1, 2, 3, 4, 5])
//. [1, 4, 9, 16, 25]
//. ```
S.flip =
def('flip',
{},
[$.Function, b, a, c],
function(f, x, y) { return f(y, x); });
//# lift :: Functor f => (a -> b) -> f a -> f b
//.
//. Promotes a unary function to a function which operates on a [Functor][].
//.
//. ```javascript
//. > S.lift(S.inc, S.Just(2))
//. Just(3)
//.
//. > S.lift(S.inc, S.Nothing())
//. Nothing()
//. ```
S.lift =
def('lift',
{a: [Functor], b: [Functor]},
[$.Function, a, b],
R.map);
//# lift2 :: Apply f => (a -> b -> c) -> f a -> f b -> f c
//.
//. Promotes a binary function to a function which operates on two
//. [Apply][]s.
//.
//. ```javascript
//. > S.lift2(S.add, S.Just(2), S.Just(3))
//. Just(5)
//.
//. > S.lift2(S.add, S.Just(2), S.Nothing())
//. Nothing()
//.
//. > S.lift2(S.and, S.Just(true), S.Just(true))
//. Just(true)
//.
//. > S.lift2(S.and, S.Just(true), S.Just(false))
//. Just(false)
//. ```
S.lift2 =
def('lift2',
{a: [Apply], b: [Apply], c: [Apply]},
[$.Function, a, b, c],
function(f, x, y) { return R.ap(R.map(f, x), y); });
//# lift3 :: Apply f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d
//.
//. Promotes a ternary function to a function which operates on three
//. [Apply][]s.
//.
//. ```javascript
//. > S.lift3(S.reduce, S.Just(S.add), S.Just(0), S.Just([1, 2, 3]))
//. Just(6)
//.
//. > S.lift3(S.reduce, S.Just(S.add), S.Just(0), S.Nothing())
//. Nothing()
//. ```
S.lift3 =
def('lift3',
{a: [Apply], b: [Apply], c: [Apply], d: [Apply]},
[$.Function, a, b, c, d],
function(f, x, y, z) { return R.ap(R.ap(R.map(f, x), y), z); });
//. ### Composition
//# compose :: (b -> c) -> (a -> b) -> a -> c
//.
//. Takes two functions assumed to be unary and a value of any type,
//. and returns the result of applying the first function to the result
//. of applying the second function to the given value.
//.
//. In general terms, `compose` performs right-to-left composition of two
//. unary functions.
//.
//. See also [`B`](#B) and [`pipe`](#pipe).
//.
//. ```javascript
//. > S.compose(Math.sqrt, S.inc)(99)
//. 10
//. ```
var compose = S.compose =
def('compose',
{},
[$.Function, $.Function, a, c],
compose3);
//# pipe :: [(a -> b), (b -> c), ..., (m -> n)] -> a -> n
//.
//. Takes an array of functions assumed to be unary and a value of any type,
//. and returns the result of applying the sequence of transformations to
//. the initial value.
//.
//. In general terms, `pipe` performs left-to-right composition of an array
//. of functions. `pipe([f, g, h], x)` is equivalent to `h(g(f(x)))`.
//.
//. See also [`meld`](#meld).
//.
//. ```javascript
//. > S.pipe([S.inc, Math.sqrt, S.dec])(99)
//. 9
//. ```
S.pipe =
def('pipe',
{},
[$.Array($.Function), a, b],
function(fs, x) { return R.reduceRight(compose2, I, fs)(x); });
//# meld :: [** -> *] -> (* -> * -> ... -> *)
//.
//. Takes an array of non-nullary functions and returns a curried function
//. whose arity is one greater than the sum of the arities of the given
//. functions less the number of functions.
//.
//. The behaviour of `meld` is best conveyed diagrammatically. The following
//. diagram depicts the "melding" of binary functions `f` and `g`:
//.
//. +-------+
//. --- a --->| |
//. | f | +-------+
//. --- b --->| |--- f(a, b) --->| |
//. +-------+ | g |
//. --- c ---------------------------->| |--- g(f(a, b), c) --->
//. +-------+
//.
//. See also [`pipe`](#pipe).
//.
//. ```javascript
//. > S.meld([Math.pow, S.sub])(3, 4, 5)
//. 76
//.
//. > S.meld([Math.pow, S.sub])(3)(4)(5)
//. 76
//. ```
S.meld =
def('meld',
{},
[$.Array($.Function), $.Function],
function(fs) {
var n = 1 + sum(R.map(R.length, fs)) - fs.length;
return R.curryN(n, function() {
var args = Array.prototype.slice.call(arguments);
for (var idx = 0; idx < fs.length; idx += 1) {
args.unshift(fs[idx].apply(this, args.splice(0, fs[idx].length)));
}
return args[0];
});
});
//. ### Maybe type
//.
//. The Maybe type represents optional values: a value of type `Maybe a` is
//. either a Just whose value is of type `a` or a Nothing (with no value).
//.
//. The Maybe type satisfies the [Monoid][], [Monad][], [Traversable][],
//. and [Extend][] specifications.
//# MaybeType :: Type -> Type
//.
//. A [`UnaryType`][UnaryType] for use with [sanctuary-def][].
//# Maybe :: TypeRep Maybe
//.
//. The [type representative](#type-representatives) for the Maybe type.
var Maybe = S.Maybe = function Maybe() {
if (arguments[0] !== sentinel) {
throw new Error('Cannot instantiate Maybe');
}
};
//# Maybe.empty :: -> Maybe a
//.
//. Returns a Nothing.
//.
//. ```javascript
//. > S.Maybe.empty()
//. Nothing()
//. ```
Maybe.empty =
def('Maybe.empty',
{},
[$Maybe(a)],
function() { return Nothing(); });
//# Maybe.of :: a -> Maybe a
//.
//. Takes a value of any type and returns a Just with the given value.
//.
//. ```javascript
//. > S.Maybe.of(42)
//. Just(42)
//. ```
Maybe.of =
def('Maybe.of',
{},
[a, $Maybe(a)],
function(x) { return Just(x); });
//# Maybe#@@type :: String
//.
//. Maybe type identifier, `'sanctuary/Maybe'`.
Maybe.prototype['@@type'] = 'sanctuary/Maybe';
//# Maybe#isNothing :: Boolean
//.
//. `true` if `this` is a Nothing; `false` if `this` is a Just.
//.
//. ```javascript
//. > S.Nothing().isNothing
//. true
//.
//. > S.Just(42).isNothing
//. false
//. ```
//# Maybe#isJust :: Boolean
//.
//. `true` if `this` is a Just; `false` if `this` is a Nothing.
//.
//. ```javascript
//. > S.Just(42).isJust
//. true
//.
//. > S.Nothing().isJust
//. false
//. ```
//# Maybe#ap :: Maybe (a -> b) ~> Maybe a -> Maybe b
//.
//. Takes a value of type `Maybe a` and returns a Nothing unless `this`
//. is a Just *and* the argument is a Just, in which case it returns a
//. Just whose value is the result of of applying this Just's value to
//. the given Just's value.
//.
//. ```javascript
//. > S.Nothing().ap(S.Just(42))
//. Nothing()
//.
//. > S.Just(S.inc).ap(S.Nothing())
//. Nothing()
//.
//. > S.Just(S.inc).ap(S.Just(42))
//. Just(43)
//. ```
Maybe.prototype.ap =
method('Maybe#ap',
{},
[$Maybe($.Function), $Maybe(a), $Maybe(b)],
function(mf, mx) { return mf.isJust ? mx.map(mf.value) : mf; });
//# Maybe#chain :: Maybe a ~> (a -> Maybe b) -> Maybe b
//.
//. Takes a function and returns `this` if `this` is a Nothing; otherwise
//. it returns the result of applying the function to this Just's value.
//.
//. ```javascript
//. > S.Nothing().chain(S.parseFloat)
//. Nothing()
//.
//. > S.Just('xxx').chain(S.parseFloat)
//. Nothing()
//.
//. > S.Just('12.34').chain(S.parseFloat)
//. Just(12.34)
//. ```
Maybe.prototype.chain =
method('Maybe#chain',
{},
[$Maybe(a), $.Function, $Maybe(b)],
function(maybe, f) { return maybe.isJust ? f(maybe.value) : maybe; });
//# Maybe#concat :: Semigroup a => Maybe a ~> Maybe a -> Maybe a
//.
//. Returns the result of concatenating two Maybe values of the same type.
//. `a` must have a [Semigroup][] (indicated by the presence of a `concat`
//. method).
//.
//. If `this` is a Nothing and the argument is a Nothing, this method returns
//. a Nothing.
//.
//. If `this` is a Just and the argument is a Just, this method returns a
//. Just whose value is the result of concatenating this Just's value and
//. the given Just's value.
//.
//. Otherwise, this method returns the Just.
//.
//. ```javascript
//. > S.Nothing().concat(S.Nothing())
//. Nothing()
//.
//. > S.Just([1, 2, 3]).concat(S.Just([4, 5, 6]))
//. Just([1, 2, 3, 4, 5, 6])
//.
//. > S.Nothing().concat(S.Just([1, 2, 3]))
//. Just([1, 2, 3])
//.
//. > S.Just([1, 2, 3]).concat(S.Nothing())
//. Just([1, 2, 3])
//. ```
Maybe.prototype.concat =
method('Maybe#concat',
{a: [Semigroup]},
[$Maybe(a), $Maybe(a), $Maybe(a)],
function(mx, my) {
return mx.isNothing ? my :
my.isNothing ? mx : Just(mx.value.concat(my.value));
});
//# Maybe#empty :: Maybe a ~> Maybe a
//.
//. Returns a Nothing.
//.
//. ```javascript
//. > S.Just(42).empty()
//. Nothing()
//. ```
Maybe.prototype.empty =
def('Maybe#empty',
{},
[$Maybe(a)],
Maybe.empty);
//# Maybe#equals :: Maybe a ~> b -> Boolean
//.
//. Takes a value of any type and returns `true` if:
//.
//. - it is a Nothing and `this` is a Nothing; or
//.
//. - it is a Just and `this` is a Just, and their values are equal
//. according to [`R.equals`][R.equals].
//.
//. ```javascript
//. > S.Nothing().equals(S.Nothing())
//. true
//.
//. > S.Nothing().equals(null)
//. false
//.
//. > S.Just([1, 2, 3]).equals(S.Just([1, 2, 3]))
//. true
//.
//. > S.Just([1, 2, 3]).equals(S.Just([3, 2, 1]))
//. false
//.
//. > S.Just([1, 2, 3]).equals(S.Nothing())
//. false
//. ```
Maybe.prototype.equals =
method('Maybe#equals',
{},
[$Maybe(a), b, $.Boolean],
function(maybe, x) {
return _type(x) === 'sanctuary/Maybe' &&
(maybe.isNothing && x.isNothing ||
maybe.isJust && x.isJust && R.eqProps('value', maybe, x));
});
//# Maybe#extend :: Maybe a ~> (Maybe a -> a) -> Maybe a
//.
//. Takes a function and returns `this` if `this` is a Nothing; otherwise
//. it returns a Just whose value is the result of applying the function to