forked from sanctuary-js/sanctuary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
3525 lines (3300 loc) · 102 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
//.
//. [![npm](https://img.shields.io/npm/v/sanctuary.svg)](https://www.npmjs.com/package/sanctuary)
//. [![CircleCI](https://img.shields.io/circleci/project/github/sanctuary-js/sanctuary/master.svg)](https://circleci.com/gh/sanctuary-js/sanctuary/tree/master)
//. [![Gitter](https://img.shields.io/gitter/room/badges/shields.svg)](https://gitter.im/sanctuary-js/sanctuary)
//.
//. Sanctuary is a functional programming library inspired by Haskell
//. and PureScript. It's stricter and more opinionated than [Ramda][],
//. and provides a similar suite of functions.
//.
//. 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:
//.
//. Z.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, is a member of `String`;
//. `[1, 2, 3]` is a member of `Array Number`. The double colon (`::`) is used
//. to mean "is a member of", so one could write:
//.
//. 'foo' :: String
//. [1, 2, 3] :: Array Number
//.
//. An identifier may appear to the left of the double colon:
//.
//. Math.PI :: Number
//.
//. The arrow (`->`) is used to express a function's type:
//.
//. Math.abs :: Number -> Number
//.
//. That states that `Math.abs` is a unary function which takes an argument
//. of type `Number` and returns a value of type `Number`.
//.
//. Some functions are parametrically polymorphic: their types are not fixed.
//. Type variables are used in the representations of such functions:
//.
//. S.I :: a -> a
//.
//. `a` is a type variable. Type variables are not capitalized, so they
//. are differentiable from type identifiers (which are always capitalized).
//. By convention type variables have single-character names. The signature
//. above states that `S.I` takes a value of any type and returns a value of
//. the same type. Some signatures feature multiple type variables:
//.
//. S.K :: a -> b -> a
//.
//. It must be possible to replace all occurrences of `a` with a concrete type.
//. The same applies for each other type variable. For the function above, the
//. types with which `a` and `b` are replaced may be different, but needn't be.
//.
//. Since all Sanctuary functions are curried (they accept their arguments
//. one at a time), a binary function is represented as a unary function which
//. returns a unary function: `* -> * -> *`. This aligns neatly with Haskell,
//. which uses curried functions exclusively. In JavaScript, though, we may
//. wish to represent the types of functions with arities less than or greater
//. than one. The general form is `(<input-types>) -> <output-type>`, where
//. `<input-types>` comprises zero or more comma–space (<code>, </code>)
//. -separated type representations:
//.
//. - `() -> String`
//. - `(a, b) -> a`
//. - `(a, b, c) -> d`
//.
//. `Number -> Number` can thus be seen as shorthand for `(Number) -> Number`.
//.
//. The question mark (`?`) is used to represent types which include `null`
//. and `undefined` as members. `String?`, for example, represents the type
//. comprising `null`, `undefined`, and all strings.
//.
//. 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 Either type, for
//. example, is created via the Left constructor or the Right 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`._
//.
//. The squiggly arrow is also used when representing non-function properties.
//. `Maybe a ~> Boolean`, for example, represents a Boolean property of a value
//. of type `Maybe a`.
//.
//. 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';
// deps :: Array String
var deps = [
'sanctuary-def',
'sanctuary-type-classes',
'sanctuary-type-identifiers'
];
/* istanbul ignore else */
if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = f(require(deps[0]), require(deps[1]), require(deps[2]));
} else if (typeof define === 'function' && define.amd != null) {
define(deps, f);
} else {
self.sanctuary = f(self.sanctuaryDef,
self.sanctuaryTypeClasses,
self.sanctuaryTypeIdentifiers);
}
}(function($, Z, type) {
'use strict';
// Fn :: (Type, Type) -> Type
function Fn(x, y) { return $.Function([x, y]); }
// Pred :: Type -> Type
function Pred(x) { return Fn(x, $.Boolean); }
// Thunk :: Type -> Type
function Thunk(x) { return $.Function([x]); }
// typeEq :: String -> a -> Boolean
function typeEq(typeIdent) {
return function(x) {
return type(x) === typeIdent;
};
}
// uncurry2 :: (a -> b -> c) -> ((a, b) -> c)
function uncurry2(f) {
return function(x, y) {
return f(x)(y);
};
}
// uncurry3 :: (a -> b -> c -> d) -> ((a, b, c) -> d)
function uncurry3(f) {
return function(x, y, z) {
return f(x)(y)(z);
};
}
// unsafeHead :: Array a -> a?
function unsafeHead(xs) { return xs[0]; }
// Accessible :: TypeClass
var Accessible = Z.TypeClass(
'sanctuary/Accessible',
[],
function(x) { return x != null; }
);
// Ord :: TypeClass
var Ord = Z.TypeClass(
'sanctuary/Ord',
[],
function(x) {
return $.String._test(x) ||
$.ValidDate._test(x) ||
$.ValidNumber._test(x);
}
);
// readmeUrl :: String -> String
function readmeUrl(id) {
var version = '0.11.1'; // updated programmatically
return 'https://github.com/sanctuary-js/sanctuary/tree/v' + version +
'#' + id;
}
var a = $.TypeVariable('a');
var b = $.TypeVariable('b');
var c = $.TypeVariable('c');
var d = $.TypeVariable('d');
var e = $.TypeVariable('e');
var f = $.UnaryTypeVariable('f');
var l = $.TypeVariable('l');
var r = $.TypeVariable('r');
// eitherTypeIdent :: String
var eitherTypeIdent = 'sanctuary/Either';
// $Either :: Type -> Type -> Type
var $Either = $.BinaryType(
eitherTypeIdent,
readmeUrl('EitherType'),
typeEq(eitherTypeIdent),
function(either) { return either.isLeft ? [either.value] : []; },
function(either) { return either.isRight ? [either.value] : []; }
);
// List :: Type -> Type
var List = $.UnaryType(
'sanctuary/List',
readmeUrl('list'),
function(x) { return $.String._test(x) || Array.isArray(x); },
function(list) { return $.String._test(list) ? [] : list; }
);
// maybeTypeIdent :: String
var maybeTypeIdent = 'sanctuary/Maybe';
// $Maybe :: Type -> Type
var $Maybe = $.UnaryType(
maybeTypeIdent,
readmeUrl('MaybeType'),
typeEq(maybeTypeIdent),
function(maybe) { return maybe.isJust ? [maybe.value] : []; }
);
// TypeRep :: Type -> Type
var TypeRep = $.UnaryType(
'sanctuary/TypeRep',
readmeUrl('type-representatives'),
function(x) {
return $.AnyFunction._test(x) ||
x != null && $.String._test(x['@@type']);
},
function(typeRep) { return []; }
);
// defaultEnv :: Array Type
var defaultEnv = Z.concat($.env, [
$.FiniteNumber,
$.NonZeroFiniteNumber,
$Either,
Fn($.Unknown, $.Unknown),
$.GlobalRegExp,
$.NonGlobalRegExp,
$.Integer,
$Maybe,
$.Pair,
$.RegexFlags,
$.ValidDate,
$.ValidNumber
]);
// Options :: Type
var Options = $.RecordType({checkTypes: $.Boolean, env: $.Array($.Any)});
// createSanctuary :: Options -> Module
function createSanctuary(opts) {
/* eslint-disable indent */
var S = {};
//# 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');
//. const type = require('sanctuary-type-identifiers');
//.
//. // identityTypeIdent :: String
//. const identityTypeIdent = 'my-package/Identity';
//.
//. // Identity :: a -> Identity a
//. function Identity(x) {
//. if (!(this instanceof Identity)) return new Identity(x);
//. this.value = x;
//. }
//.
//. Identity['@@type'] = identityTypeIdent;
//.
//. Identity.prototype['fantasy-land/map'] = function(f) {
//. return Identity(f(this.value));
//. };
//.
//. Identity.prototype['fantasy-land/chain'] = function(f) {
//. return f(this.value);
//. };
//.
//. // isIdentity :: a -> Boolean
//. const isIdentity = x => type(x) === identityTypeIdent;
//.
//. // identityToArray :: Identity a -> Array a
//. const identityToArray = identity => [identity.value];
//.
//. // IdentityType :: Type
//. const IdentityType =
//. $.UnaryType(identityTypeIdent, 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);
//. ### Placeholder
//.
//. Sanctuary functions are designed with partial application in mind.
//. In many cases one can define a more specific function in terms of
//. a more general one simply by applying the more general function to
//. some (but not all) of its arguments. For example, one could define
//. `sum :: Foldable f => f Number -> Number` as `S.reduce(S.add, 0)`.
//.
//. In some cases, though, there are multiple orders in which one may
//. wish to provide a function's arguments. `S.concat('prefix')` is a
//. function which prefixes its argument, but how would one define a
//. function which suffixes its argument? It's possible with the help
//. of [`__`](#__), the special placeholder value.
//.
//. The placeholder indicates a hole to be filled at some future time.
//. The following are all equivalent (`_` represents the placeholder):
//.
//. - `f(x, y, z)`
//. - `f(_, y, z)(x)`
//. - `f(_, _, z)(x, y)`
//. - `f(_, _, z)(_, y)(x)`
//# __ :: Placeholder
//.
//. The special [placeholder](#placeholder) value.
//.
//. ```javascript
//. > Z.map(S.concat('@'), ['foo', 'bar', 'baz'])
//. ['@foo', '@bar', '@baz']
//.
//. > Z.map(S.concat(S.__, '?'), ['foo', 'bar', 'baz'])
//. ['foo?', 'bar?', 'baz?']
//. ```
S.__ = $.__;
//. ### Classify
//# type :: Any -> String
//.
//. Takes a value, `x`, of any type and returns its [type identifier][].
//.
//. ```javascript
//. > S.type(S.Just(42))
//. 'sanctuary/Maybe'
//.
//. > S.type([1, 2, 3])
//. 'Array'
//. ```
S.type = def('type', {}, [$.Any, $.String], type);
//# is :: TypeRep a -> Any -> 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
//. ```
function is(typeRep, x) {
var xType = type(x);
if ($.String._test(typeRep['@@type'])) {
return xType === typeRep['@@type'];
} else {
var match = /function (\w*)/.exec(typeRep);
return match != null && match[1] === xType;
}
}
S.is = def('is', {}, [TypeRep(a), $.Any, $.Boolean], is);
//. ### Combinator
//# I :: a -> a
//.
//. The I combinator. Returns its argument. Equivalent to Haskell's `id`
//. function.
//.
//. ```javascript
//. > S.I('foo')
//. 'foo'
//. ```
function I(x) {
return x;
}
S.I = def('I', {}, [a, a], I);
//# 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'
//.
//. > Z.map(S.K(42), S.range(0, 5))
//. [42, 42, 42, 42, 42]
//. ```
function K(x, y) {
return x;
}
S.K = def('K', {}, [a, b, a], K);
//# 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
//.
//. > Z.map(S.A(S.__, 100), [S.inc, Math.sqrt])
//. [101, 10]
//. ```
function A(f, x) {
return f(x);
}
S.A = def('A', {}, [Fn(a, b), a, b], A);
//# 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
//.
//. > Z.map(S.T(100), [S.inc, Math.sqrt])
//. [101, 10]
//. ```
function T(x, f) {
return f(x);
}
S.T = def('T', {}, [a, Fn(a, b), b], T);
//# 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
//. ```
function S_(f, g, x) {
return f(x)(g(x));
}
S.S = def('S', {}, [Fn(a, Fn(b, c)), Fn(a, b), a, c], S_);
//. ### Function
//# curry2 :: ((a, b) -> c) -> a -> b -> c
//.
//. Curries the given binary function.
//.
//. ```javascript
//. > Z.map(S.curry2(Math.pow)(10), [1, 2, 3])
//. [10, 100, 1000]
//.
//. > Z.map(S.curry2(Math.pow, 10), [1, 2, 3])
//. [10, 100, 1000]
//. ```
function curry2(f, x, y) {
return f(x, y);
}
S.curry2 =
def('curry2',
{},
[$.Function([a, b, c]), a, b, c],
curry2);
//# curry3 :: ((a, b, c) -> d) -> a -> b -> c -> d
//.
//. Curries the given ternary function.
//.
//. ```javascript
//. > global.replaceString = S.curry3((what, replacement, string) =>
//. . string.replace(what, replacement)
//. . )
//. replaceString
//.
//. > replaceString('banana')('orange')('banana icecream')
//. 'orange icecream'
//.
//. > replaceString('banana', 'orange', 'banana icecream')
//. 'orange icecream'
//. ```
function curry3(f, x, y, z) {
return f(x, y, z);
}
S.curry3 =
def('curry3',
{},
[$.Function([a, b, c, d]), a, b, c, d],
curry3);
//# curry4 :: ((a, b, c, d) -> e) -> a -> b -> c -> d -> e
//.
//. Curries the given quaternary function.
//.
//. ```javascript
//. > global.createRect = S.curry4((x, y, width, height) =>
//. . ({x, y, width, height})
//. . )
//. createRect
//.
//. > createRect(0)(0)(10)(10)
//. {x: 0, y: 0, width: 10, height: 10}
//.
//. > createRect(0, 0, 10, 10)
//. {x: 0, y: 0, width: 10, height: 10}
//. ```
function curry4(f, w, x, y, z) {
return f(w, x, y, z);
}
S.curry4 =
def('curry4',
{},
[$.Function([a, b, c, d, e]), a, b, c, d, e],
curry4);
//# curry5 :: ((a, b, c, d, e) -> f) -> a -> b -> c -> d -> e -> f
//.
//. Curries the given quinary function.
//.
//. ```javascript
//. > global.toUrl = S.curry5((protocol, creds, hostname, port, pathname) =>
//. . protocol + '//' +
//. . S.maybe('', _ => _.username + ':' + _.password + '@', creds) +
//. . hostname +
//. . S.maybe('', S.concat(':'), port) +
//. . pathname
//. . )
//. toUrl
//.
//. > toUrl('https:')(S.Nothing)('example.com')(S.Just('443'))('/foo/bar')
//. 'https://example.com:443/foo/bar'
//.
//. > toUrl('https:', S.Nothing, 'example.com', S.Just('443'), '/foo/bar')
//. 'https://example.com:443/foo/bar'
//. ```
function curry5(f, v, w, x, y, z) {
return f(v, w, x, y, z);
}
S.curry5 =
def('curry5',
{},
[$.Function([a, b, c, d, e, r]), a, b, c, d, e, r],
curry5);
//# flip :: (a -> b -> c) -> b -> a -> c
//.
//. Takes a curried binary function and two values, and returns the
//. result of applying the function to the values in reverse order.
//.
//. This is the C combinator from combinatory logic.
//.
//. ```javascript
//. > S.flip(S.concat, 'foo', 'bar')
//. 'barfoo'
//. ```
function flip(f, x, y) {
return f(y)(x);
}
S.flip = def('flip', {}, [Fn(a, Fn(b, c)), b, a, c], flip);
//# flip_ :: ((a, b) -> c) -> b -> a -> c
//.
//. Variant of [`flip`](#flip) which takes an uncurried binary function.
function flip_(f, x, y) {
return f(y, x);
}
S.flip_ = def('flip_', {}, [$.Function([a, b, c]), b, a, c], flip_);
//# 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', {f: [Z.Functor]}, [Fn(a, b), f(a), f(b)], Z.map);
//# lift2 :: Apply f => (a -> b -> c) -> f a -> f b -> f c
//.
//. Promotes a curried 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', {f: [Z.Apply]}, [Fn(a, Fn(b, c)), f(a), f(b), f(c)], Z.lift2);
//# lift3 :: Apply f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d
//.
//. Promotes a curried 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',
{f: [Z.Apply]},
[Fn(a, Fn(b, Fn(c, d))), f(a), f(b), f(c), f(d)],
Z.lift3);
//. ### Composition
//# compose :: (b -> c) -> (a -> b) -> a -> c
//.
//. Composes two unary functions, from right to left. Equivalent to Haskell's
//. `(.)` function.
//.
//. This is the B combinator from combinatory logic.
//.
//. See also [`pipe`](#pipe).
//.
//. ```javascript
//. > S.compose(Math.sqrt, S.inc)(99)
//. 10
//. ```
function compose(f, g, x) {
return f(g(x));
}
S.compose = def('compose', {}, [Fn(b, c), Fn(a, b), a, c], compose);
//# 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)))`.
//.
//. ```javascript
//. > S.pipe([S.inc, Math.sqrt, S.dec])(99)
//. 9
//. ```
function pipe(fs, x) {
return Z.reduce(function(x, f) { return f(x); }, x, fs);
}
S.pipe = def('pipe', {}, [$.Array($.AnyFunction), a, b], pipe);
//# on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
//.
//. Takes a binary function `f`, a unary function `g`, and two
//. values `x` and `y`. Returns `f(g(x))(g(y))`.
//.
//. See also [`on_`](#on_).
//.
//. ```javascript
//. > S.on(S.concat, S.reverse, [1, 2, 3], [4, 5, 6])
//. [3, 2, 1, 6, 5, 4]
//. ```
function on(f, g, x, y) {
return on_(uncurry2(f), g, x, y);
}
S.on = def('on', {}, [Fn(b, Fn(b, c)), Fn(a, b), a, a, c], on);
//# on_ :: ((b, b) -> c) -> (a -> b) -> a -> a -> c
//.
//. Variant of [`on`](#on) which takes an uncurried binary function.
function on_(f, g, x, y) {
return f(g(x), g(y));
}
S.on_ = def('on_', {}, [$.Function([b, b, c]), Fn(a, b), a, a, c], on_);
//. ### 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 Nothing (with no value).
//.
//. The Maybe type satisfies the [Setoid][], [Monoid][], [Monad][],
//. [Alternative][], [Traversable][], and [Extend][] specifications.
//# MaybeType :: Type -> Type
//.
//. A [`UnaryType`][UnaryType] for use with [sanctuary-def][].
S.MaybeType = $Maybe;
//# Maybe :: TypeRep Maybe
//.
//. The [type representative](#type-representatives) for the Maybe type.
var Maybe = S.Maybe = {prototype: _Maybe.prototype};
Maybe.prototype.constructor = Maybe;
function _Maybe(tag, value) {
this.isNothing = tag === 'Nothing';
this.isJust = tag === 'Just';
if (this.isJust) this.value = value;
}
//# Nothing :: Maybe a
//.
//. Nothing.
//.
//. ```javascript
//. > S.Nothing
//. Nothing
//. ```
var Nothing = S.Nothing = new _Maybe('Nothing');
//# Just :: a -> Maybe a
//.
//. Takes a value of any type and returns a Just with the given value.
//.
//. ```javascript
//. > S.Just(42)
//. Just(42)
//. ```
function Just(x) {
return new _Maybe('Just', x);
}
S.Just = def('Just', {}, [a, $Maybe(a)], Just);
//# Maybe.@@type :: String
//.
//. Maybe type identifier, `'sanctuary/Maybe'`.
Maybe['@@type'] = maybeTypeIdent;
//# Maybe.fantasy-land/empty :: () -> Maybe a
//.
//. Returns Nothing.
//.
//. ```javascript
//. > Z.empty(S.Maybe)
//. Nothing
//. ```
Maybe['fantasy-land/empty'] = function() { return Nothing; };
//# Maybe.fantasy-land/of :: a -> Maybe a
//.
//. Takes a value of any type and returns a Just with the given value.
//.
//. ```javascript
//. > Z.of(S.Maybe, 42)
//. Just(42)
//. ```
Maybe['fantasy-land/of'] = Just;
//# Maybe.fantasy-land/zero :: () -> Maybe a
//.
//. Returns Nothing.
//.
//. ```javascript
//. > Z.zero(S.Maybe)
//. Nothing
//. ```
Maybe['fantasy-land/zero'] = function() { return Nothing; };
//# Maybe#isNothing :: Maybe a ~> Boolean
//.
//. `true` if `this` is Nothing; `false` if `this` is a Just.
//.
//. ```javascript
//. > S.Nothing.isNothing
//. true
//.
//. > S.Just(42).isNothing
//. false
//. ```
//# Maybe#isJust :: Maybe a ~> Boolean
//.
//. `true` if `this` is a Just; `false` if `this` is Nothing.
//.
//. ```javascript
//. > S.Just(42).isJust
//. true
//.
//. > S.Nothing.isJust
//. false
//. ```
//# Maybe#toString :: Maybe a ~> () -> String
//.
//. Returns the string representation of the Maybe.
//.
//. ```javascript
//. > Z.toString(S.Nothing)
//. 'Nothing'
//.
//. > Z.toString(S.Just([1, 2, 3]))
//. 'Just([1, 2, 3])'
//. ```
Maybe.prototype.toString = function() {
return this.isJust ? 'Just(' + Z.toString(this.value) + ')' : 'Nothing';
};
//# Maybe#inspect :: Maybe a ~> () -> String
//.
//. Returns the string representation of the Maybe. This method is used by
//. `util.inspect` and the REPL to format a Maybe for display.
//.
//. See also [`Maybe#toString`][].
//.
//. ```javascript
//. > S.Nothing.inspect()
//. 'Nothing'
//.
//. > S.Just([1, 2, 3]).inspect()
//. 'Just([1, 2, 3])'
//. ```
Maybe.prototype.inspect = function() { return this.toString(); };
//# Maybe#fantasy-land/equals :: Maybe a ~> Maybe a -> Boolean
//.
//. Takes a value of the same type and returns `true` if:
//.
//. - it is Nothing and `this` is Nothing; or
//.
//. - it is a Just and `this` is a Just, and their values are equal
//. according to [`Z.equals`][Z.equals].
//.
//. ```javascript
//. > Z.equals(S.Nothing, S.Nothing)
//. true
//.
//. > Z.equals(S.Nothing, null)
//. false
//.
//. > Z.equals(S.Just([1, 2, 3]), S.Just([1, 2, 3]))
//. true
//.
//. > Z.equals(S.Just([1, 2, 3]), S.Just([3, 2, 1]))
//. false
//.
//. > Z.equals(S.Just([1, 2, 3]), S.Nothing)
//. false
//. ```
Maybe.prototype['fantasy-land/equals'] = function(other) {
return this.isNothing ? other.isNothing
: other.isJust && Z.equals(other.value, this.value);
};
//# Maybe#fantasy-land/concat :: Semigroup a => Maybe a ~> Maybe a -> Maybe a
//.