-
-
Notifications
You must be signed in to change notification settings - Fork 95
/
index.js
4882 lines (4657 loc) · 133 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 JavaScript functional programming library inspired by
//. [Haskell][] and [PureScript][]. It's stricter than [Ramda][], and
//. provides a similar suite of functions.
//.
//. Sanctuary promotes programs composed of simple, pure functions. Such
//. programs are easier to comprehend, test, and maintain – they are
//. also a pleasure to write.
//.
//. Sanctuary provides two data types, [Maybe][] and [Either][], both of
//. which are compatible with [Fantasy Land][]. Thanks to these data types
//. even Sanctuary functions that may fail, such as [`head`](#head), are
//. composable.
//.
//. 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:
//.
//. S.map (S.toUpper) (S.head (words))
//.
//. Sanctuary is designed to work in Node.js and in ES5-compatible browsers.
//.
//. ## Folktale
//.
//. [Folktale][], like Sanctuary, is a standard library for functional
//. programming in JavaScript. It is well designed and well documented.
//. Whereas Sanctuary treats JavaScript as a member of the ML language
//. family, Folktale embraces JavaScript's object-oriented programming
//. model. Programming with Folktale resembles programming with Scala.
//.
//. ## Ramda
//.
//. [Ramda][] provides several functions that return problematic values
//. such as `undefined`, `Infinity`, or `NaN` when applied to unsuitable
//. inputs. These are known as [partial functions][]. Partial functions
//. necessitate the use of guards or null checks. In order to safely use
//. `R.head`, for example, one must ensure that the array is non-empty:
//.
//. if (R.isEmpty (xs)) {
//. // ...
//. } else {
//. return f (R.head (xs));
//. }
//.
//. Using the Maybe type renders such guards (and null checks) unnecessary.
//. Changing functions such as `R.head` to return Maybe values was proposed
//. in [ramda/ramda#683][], but was considered too much of a stretch for
//. JavaScript programmers. Sanctuary was released the following month,
//. in January 2015, as a companion library to Ramda.
//.
//. In addition to broadening in scope in the years since its release,
//. Sanctuary's philosophy has diverged from Ramda's in several respects.
//.
//. ### Totality
//.
//. Every Sanctuary function is defined for every value that is a member of
//. the function's input type. Such functions are known as [total functions][].
//. Ramda, on the other hand, contains a number of [partial functions][].
//.
//. ### Information preservation
//.
//. Certain Sanctuary functions preserve more information than their Ramda
//. counterparts. Examples:
//.
//. |> R.tail ([]) |> S.tail ([])
//. [] Nothing
//.
//. |> R.tail (['foo']) |> S.tail (['foo'])
//. [] Just ([])
//.
//. |> R.replace (/^x/) ('') ('abc') |> S.stripPrefix ('x') ('abc')
//. 'abc' Nothing
//.
//. |> R.replace (/^x/) ('') ('xabc') |> S.stripPrefix ('x') ('xabc')
//. 'abc' Just ('abc')
//.
//. ### Invariants
//.
//. Sanctuary performs rigorous [type checking][] of inputs and outputs, and
//. throws a descriptive error if a type error is encountered. This allows bugs
//. to be caught and fixed early in the development cycle.
//.
//. Ramda operates on the [garbage in, garbage out][GIGO] principle. Functions
//. are documented to take arguments of particular types, but these invariants
//. are not enforced. The problem with this approach in a language as
//. permissive as JavaScript is that there's no guarantee that garbage input
//. will produce garbage output ([ramda/ramda#1413][]). Ramda performs ad hoc
//. type checking in some such cases ([ramda/ramda#1419][]).
//.
//. Sanctuary can be configured to operate in garbage in, garbage out mode.
//. Ramda cannot be configured to enforce its invariants.
//.
//. ### Currying
//.
//. Sanctuary functions are curried. There is, for example, exactly one way to
//. apply `S.reduce` to `S.add`, `0`, and `xs`:
//.
//. - `S.reduce (S.add) (0) (xs)`
//.
//. Ramda functions are also curried, but in a complex manner. There are four
//. ways to apply `R.reduce` to `R.add`, `0`, and `xs`:
//.
//. - `R.reduce (R.add) (0) (xs)`
//. - `R.reduce (R.add) (0, xs)`
//. - `R.reduce (R.add, 0) (xs)`
//. - `R.reduce (R.add, 0, xs)`
//.
//. Ramda supports all these forms because curried functions enable partial
//. application, one of the library's tenets, but `f(x)(y)(z)` is considered
//. too unfamiliar and too unattractive to appeal to JavaScript programmers.
//.
//. Sanctuary's developers prefer a simple, unfamiliar construct to a complex,
//. familiar one. Familiarity can be acquired; complexity is intrinsic.
//.
//. The lack of breathing room in `f(x)(y)(z)` impairs readability. The simple
//. solution to this problem, proposed in [#438][], is to include a space when
//. applying a function: `f (x) (y) (z)`.
//.
//. Ramda also provides a special placeholder value, [`R.__`][], that removes
//. the restriction that a function must be applied to its arguments in order.
//. The following expressions are equivalent:
//.
//. - `R.reduce (R.__, 0, xs) (R.add)`
//. - `R.reduce (R.add, R.__, xs) (0)`
//. - `R.reduce (R.__, 0) (R.add) (xs)`
//. - `R.reduce (R.__, 0) (R.add, xs)`
//. - `R.reduce (R.__, R.__, xs) (R.add) (0)`
//. - `R.reduce (R.__, R.__, xs) (R.add, 0)`
//.
//. ### Variadic functions
//.
//. Ramda provides several functions that take any number of arguments. These
//. are known as [variadic functions][]. Additionally, Ramda provides several
//. functions that take variadic functions as arguments. Although natural in
//. a dynamically typed language, variadic functions are at odds with the type
//. notation Ramda and Sanctuary both use, leading to some indecipherable type
//. signatures such as this one:
//.
//. R.lift :: (*... -> *...) -> ([*]... -> [*])
//.
//. Sanctuary has no variadic functions, nor any functions that take variadic
//. functions as arguments. Sanctuary provides two "lift" functions, each with
//. a helpful type signature:
//.
//. S.lift2 :: Apply f => (a -> b -> c) -> f a -> f b -> f c
//. S.lift3 :: Apply f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d
//.
//. ### Implicit context
//.
//. Ramda provides [`R.bind`][] and [`R.invoker`][] for working with methods.
//. Additionally, many Ramda functions use `Function#call` or `Function#apply`
//. to preserve context. Sanctuary makes no allowances for `this`.
//.
//. ### Transducers
//.
//. Several Ramda functions act as transducers. Sanctuary provides no support
//. for transducers.
//.
//. ### Modularity
//.
//. Whereas Ramda has no dependencies, Sanctuary has a modular design:
//. [sanctuary-def][] provides type checking, [sanctuary-type-classes][]
//. provides Fantasy Land functions and type classes, [sanctuary-show][]
//. provides string representations, and algebraic data types are provided
//. by [sanctuary-either][], [sanctuary-maybe][], and [sanctuary-pair][].
//. Not only does this approach reduce the complexity of Sanctuary itself,
//. but it allows these components to be reused in other contexts.
//.
//. ## 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 that 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 that
//. 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`.
//.
//. Sanctuary embraces types. JavaScript doesn't support algebraic data types,
//. but these can be simulated by providing a group of data constructors that
//. 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 `fantasy-land/map` method
//. of the Maybe type is written `Maybe a ~> (a -> b) -> Maybe b`. One could
//. read this as:
//.
//. _When the `fantasy-land/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 that 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
//. (`=>`).
//.
//. ## 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.add (2) (true);
//. // ! TypeError: Invalid value
//. //
//. // add :: FiniteNumber -> FiniteNumber -> FiniteNumber
//. // ^^^^^^^^^^^^
//. // 1
//. //
//. // 1) true :: Boolean
//. //
//. // The value at position 1 is not a member of ‘FiniteNumber’.
//. //
//. // See v:sanctuary-js/sanctuary-def#FiniteNumber for information about the FiniteNumber type.
//. ```
//.
//. Compare this to the behaviour of Ramda's unchecked equivalent:
//.
//. ```javascript
//. R.add (2) (true);
//. // => 3
//. ```
//.
//. There is a performance cost to run-time type checking. Type checking is
//. disabled by default if `process.env.NODE_ENV` is `'production'`. If this
//. rule is unsuitable for a given program, one may use [`create`](#create)
//. to create a Sanctuary module based on a different rule. For example:
//.
//. ```javascript
//. const S = sanctuary.create ({
//. checkTypes: localStorage.getItem ('SANCTUARY_CHECK_TYPES') === 'true',
//. env: sanctuary.env,
//. });
//. ```
//.
//. Occasionally one may wish to perform an operation that is not type safe,
//. such as mapping over an object with heterogeneous values. This is possible
//. via selective use of [`unchecked`](#unchecked) functions.
//.
//. ## Installation
//.
//. `npm install sanctuary` will install Sanctuary for use in Node.js.
//.
//. To add Sanctuary to a website, add the following `<script>` element,
//. replacing `X.Y.Z` with a version number greater than or equal to `2.0.2`:
//.
//. ```html
//. <script src="https://cdn.jsdelivr.net/gh/sanctuary-js/[email protected]/dist/bundle.js"></script>
//. ```
//.
//. Optionally, define aliases for various modules:
//.
//. ```javascript
//. const S = window.sanctuary;
//. const $ = window.sanctuaryDef;
//. // ...
//. ```
//.
//. ## API
(function(f) {
'use strict';
/* istanbul ignore else */
if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = f (require ('sanctuary-def'),
require ('sanctuary-either'),
require ('sanctuary-maybe'),
require ('sanctuary-pair'),
require ('sanctuary-show'),
require ('sanctuary-type-classes'),
require ('sanctuary-type-identifiers'));
} else if (typeof define === 'function' && define.amd != null) {
define (['sanctuary-def',
'sanctuary-either',
'sanctuary-maybe',
'sanctuary-pair',
'sanctuary-show',
'sanctuary-type-classes',
'sanctuary-type-identifiers'],
f);
} else {
self.sanctuary = f (self.sanctuaryDef,
self.sanctuaryEither,
self.sanctuaryMaybe,
self.sanctuaryPair,
self.sanctuaryShow,
self.sanctuaryTypeClasses,
self.sanctuaryTypeIdentifiers);
}
} (function($, Either, Maybe, Pair, show, Z, type) {
'use strict';
/* istanbul ignore if */
if (typeof __doctest !== 'undefined') {
/* eslint-disable no-unused-vars */
var Descending = __doctest.require ('sanctuary-descending');
var Nil = (__doctest.require ('./test/internal/List')).Nil;
var Cons = (__doctest.require ('./test/internal/List')).Cons;
var Sum = __doctest.require ('./test/internal/Sum');
var S = (function(S) {
var S_ = S.create ({
checkTypes: true,
env: S.env.concat ([
(__doctest.require ('./test/internal/List')).Type ($.Unknown),
Sum.Type
])
});
S_.env = S.env; // see S.env doctest
return S_;
} (require ('.')));
/* eslint-enable no-unused-vars */
}
// Left :: a -> Either a b
var Left = Either.Left;
// Right :: b -> Either a b
var Right = Either.Right;
// Nothing :: Maybe a
var Nothing = Maybe.Nothing;
// Just :: a -> Maybe a
var Just = Maybe.Just;
// B :: (b -> c) -> (a -> b) -> a -> c
function B(f) {
return function(g) {
return function(x) {
return f (g (x));
};
};
}
// C :: (a -> b -> c) -> b -> a -> c
function C(f) {
return function(y) {
return function(x) {
return f (x) (y);
};
};
}
// get_ :: String -> a -> Maybe b
function get_(key) {
return B (function(obj) { return key in obj ? Just (obj[key]) : Nothing; })
(toObject);
}
// invoke0 :: String -> a -> b
function invoke0(name) {
return function(target) {
return target[name] ();
};
}
// invoke1 :: String -> a -> b -> c
function invoke1(name) {
return function(x) {
return function(target) {
return target[name] (x);
};
};
}
// toObject :: a -> Object
function toObject(x) {
return x == null ? Object.create (null) : Object (x);
}
// :: Type
var a = $.TypeVariable ('a');
var b = $.TypeVariable ('b');
var c = $.TypeVariable ('c');
var d = $.TypeVariable ('d');
var e = $.TypeVariable ('e');
var g = $.TypeVariable ('g');
var r = $.TypeVariable ('r');
// :: Type -> Type
var f = $.UnaryTypeVariable ('f');
var m = $.UnaryTypeVariable ('m');
var t = $.UnaryTypeVariable ('t');
var w = $.UnaryTypeVariable ('w');
// :: Type -> Type -> Type
var p = $.BinaryTypeVariable ('p');
var s = $.BinaryTypeVariable ('s');
// Throwing :: Type -> Type -> Type -> Type
//
// `Throwing e a b` is the type of functions from `a` to `b` that may
// throw values of type `e`.
function Throwing(E) {
return function(A) {
return function(B) {
var T = $.Fn (A) (B);
T.format = function(outer, inner) {
return outer ('Throwing ' + show (E)) +
outer (' ') + inner ('$1') (show (A)) +
outer (' ') + inner ('$2') (show (B));
};
return T;
};
};
}
// TypeRep :: Type -> Type
var TypeRep = $.UnaryType
('TypeRep')
('https://github.com/fantasyland/fantasy-land#type-representatives')
([])
(K (true))
(K ([]));
// Options :: Type
var Options = $.RecordType ({checkTypes: $.Boolean, env: $.Array ($.Any)});
var _ = {};
//. ### Configure
//# 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 that is aware of that type:
//.
//. ```javascript
//. const {create, env} = require ('sanctuary');
//. const $ = require ('sanctuary-def');
//. const type = require ('sanctuary-type-identifiers');
//.
//. // Identity :: a -> Identity a
//. const Identity = x => {
//. const identity = Object.create (Identity$prototype);
//. identity.value = x;
//. return identity;
//. };
//.
//. // identityTypeIdent :: String
//. const identityTypeIdent = 'my-package/Identity@1';
//.
//. const Identity$prototype = {
//. '@@type': identityTypeIdent,
//. '@@show': function() { return `Identity (${S.show (this.value)})`; },
//. 'fantasy-land/map': function(f) { return Identity (f (this.value)); },
//. };
//.
//. // IdentityType :: Type -> Type
//. const IdentityType = $.UnaryType
//. ('Identity')
//. ('http://example.com/my-package#Identity')
//. ([])
//. (x => type (x) === identityTypeIdent)
//. (identity => [identity.value]);
//.
//. const S = create ({
//. checkTypes: process.env.NODE_ENV !== 'production',
//. env: env.concat ([IdentityType ($.Unknown)]),
//. });
//.
//. S.map (S.sub (1)) (Identity (43));
//. // => Identity (42)
//. ```
//.
//. See also [`env`](#env).
function create(opts) {
var def = $.create (opts);
var S = {
env: opts.env,
is: def ('is') ({}) ([$.Type, $.Any, $.Boolean]) ($.test (opts.env)),
Maybe: Maybe,
Nothing: Nothing,
Either: Either
};
(Object.keys (_)).forEach (function(name) {
S[name] = def (name) (_[name].consts) (_[name].types) (_[name].impl);
});
S.unchecked = opts.checkTypes ? create ({checkTypes: false, env: opts.env})
: S;
return S;
}
_.create = {
consts: {},
types: [Options, $.Object],
impl: create
};
//# env :: Array Type
//.
//. The Sanctuary module's environment (`(S.create ({checkTypes, env})).env`
//. is a reference to `env`). Useful in conjunction with [`create`](#create).
//.
//. ```javascript
//. > S.env
//. [ $.AnyFunction,
//. . $.Arguments,
//. . $.Array ($.Unknown),
//. . $.Array2 ($.Unknown) ($.Unknown),
//. . $.Boolean,
//. . $.Buffer,
//. . $.Date,
//. . $.Descending ($.Unknown),
//. . $.Either ($.Unknown) ($.Unknown),
//. . $.Error,
//. . $.Fn ($.Unknown) ($.Unknown),
//. . $.HtmlElement,
//. . $.Identity ($.Unknown),
//. . $.JsMap ($.Unknown) ($.Unknown),
//. . $.JsSet ($.Unknown),
//. . $.Maybe ($.Unknown),
//. . $.Module,
//. . $.Null,
//. . $.Number,
//. . $.Object,
//. . $.Pair ($.Unknown) ($.Unknown),
//. . $.RegExp,
//. . $.StrMap ($.Unknown),
//. . $.String,
//. . $.Symbol,
//. . $.Type,
//. . $.TypeClass,
//. . $.Undefined ]
//. ```
//# unchecked :: Module
//.
//. A complete Sanctuary module that performs no type checking. This is
//. useful as it permits operations that Sanctuary's type checking would
//. disallow, such as mapping over an object with heterogeneous values.
//.
//. See also [`create`](#create).
//.
//. ```javascript
//. > S.unchecked.map (S.show) ({x: 'foo', y: true, z: 42})
//. {x: '"foo"', y: 'true', z: '42'}
//. ```
//.
//. Opting out of type checking may cause type errors to go unnoticed.
//.
//. ```javascript
//. > S.unchecked.add (2) ('2')
//. '22'
//. ```
//. ### Classify
//# type :: Any -> { namespace :: Maybe String, name :: String, version :: NonNegativeInteger }
//.
//. Returns the result of parsing the [type identifier][] of the given value.
//.
//. ```javascript
//. > S.type (S.Just (42))
//. {namespace: Just ('sanctuary-maybe'), name: 'Maybe', version: 1}
//.
//. > S.type ([1, 2, 3])
//. {namespace: Nothing, name: 'Array', version: 0}
//. ```
function type_(x) {
var r = type.parse (type (x));
r.namespace = Z.reject (equals (null), Just (r.namespace));
return r;
}
_.type = {
consts: {},
types: [$.Any,
$.RecordType ({namespace: $.Maybe ($.String),
name: $.String,
version: $.NonNegativeInteger})],
impl: type_
};
//# is :: Type -> Any -> Boolean
//.
//. Returns `true` [iff][] the given value is a member of the specified type.
//. See [`$.test`][] for details.
//.
//. ```javascript
//. > S.is ($.Array ($.Integer)) ([1, 2, 3])
//. true
//.
//. > S.is ($.Array ($.Integer)) ([1, 2, 3.14])
//. false
//. ```
//. ### Showable
//# show :: Any -> String
//.
//. Alias of [`show`][].
//.
//. ```javascript
//. > S.show (-0)
//. '-0'
//.
//. > S.show (['foo', 'bar', 'baz'])
//. '["foo", "bar", "baz"]'
//.
//. > S.show ({x: 1, y: 2, z: 3})
//. '{"x": 1, "y": 2, "z": 3}'
//.
//. > S.show (S.Left (S.Right (S.Just (S.Nothing))))
//. 'Left (Right (Just (Nothing)))'
//. ```
_.show = {
consts: {},
types: [$.Any, $.String],
impl: show
};
//. ### Fantasy Land
//.
//. Sanctuary is compatible with the [Fantasy Land][] specification.
//# equals :: Setoid a => a -> a -> Boolean
//.
//. Curried version of [`Z.equals`][] that requires two arguments of the
//. same type.
//.
//. To compare values of different types first use [`create`](#create) to
//. create a Sanctuary module with type checking disabled, then use that
//. module's `equals` function.
//.
//. ```javascript
//. > S.equals (0) (-0)
//. true
//.
//. > S.equals (NaN) (NaN)
//. true
//.
//. > S.equals (S.Just ([1, 2, 3])) (S.Just ([1, 2, 3]))
//. true
//.
//. > S.equals (S.Just ([1, 2, 3])) (S.Just ([1, 2, 4]))
//. false
//. ```
function equals(x) {
return function(y) {
return Z.equals (x, y);
};
}
_.equals = {
consts: {a: [Z.Setoid]},
types: [a, a, $.Boolean],
impl: equals
};
//# lt :: Ord a => a -> a -> Boolean
//.
//. Returns `true` [iff][] the *second* argument is less than the first
//. according to [`Z.lt`][].
//.
//. ```javascript
//. > S.filter (S.lt (3)) ([1, 2, 3, 4, 5])
//. [1, 2]
//. ```
function lt(y) {
return function(x) {
return Z.lt (x, y);
};
}
_.lt = {
consts: {a: [Z.Ord]},
types: [a, a, $.Boolean],
impl: lt
};
//# lte :: Ord a => a -> a -> Boolean
//.
//. Returns `true` [iff][] the *second* argument is less than or equal to
//. the first according to [`Z.lte`][].
//.
//. ```javascript
//. > S.filter (S.lte (3)) ([1, 2, 3, 4, 5])
//. [1, 2, 3]
//. ```
function lte(y) {
return function(x) {
return Z.lte (x, y);
};
}
_.lte = {
consts: {a: [Z.Ord]},
types: [a, a, $.Boolean],
impl: lte
};
//# gt :: Ord a => a -> a -> Boolean
//.
//. Returns `true` [iff][] the *second* argument is greater than the first
//. according to [`Z.gt`][].
//.
//. ```javascript
//. > S.filter (S.gt (3)) ([1, 2, 3, 4, 5])
//. [4, 5]
//. ```
function gt(y) {
return function(x) {
return Z.gt (x, y);
};
}
_.gt = {
consts: {a: [Z.Ord]},
types: [a, a, $.Boolean],
impl: gt
};
//# gte :: Ord a => a -> a -> Boolean
//.
//. Returns `true` [iff][] the *second* argument is greater than or equal
//. to the first according to [`Z.gte`][].
//.
//. ```javascript
//. > S.filter (S.gte (3)) ([1, 2, 3, 4, 5])
//. [3, 4, 5]
//. ```
function gte(y) {
return function(x) {
return Z.gte (x, y);
};
}
_.gte = {
consts: {a: [Z.Ord]},
types: [a, a, $.Boolean],
impl: gte
};
//# min :: Ord a => a -> a -> a
//.
//. Returns the smaller of its two arguments (according to [`Z.lte`][]).
//.
//. See also [`max`](#max).
//.
//. ```javascript
//. > S.min (10) (2)
//. 2
//.
//. > S.min (new Date ('1999-12-31')) (new Date ('2000-01-01'))
//. new Date ('1999-12-31')
//.
//. > S.min ('10') ('2')
//. '10'
//. ```
_.min = {
consts: {a: [Z.Ord]},
types: [a, a, a],
impl: curry2 (Z.min)
};
//# max :: Ord a => a -> a -> a
//.
//. Returns the larger of its two arguments (according to [`Z.lte`][]).
//.
//. See also [`min`](#min).
//.
//. ```javascript
//. > S.max (10) (2)
//. 10
//.
//. > S.max (new Date ('1999-12-31')) (new Date ('2000-01-01'))
//. new Date ('2000-01-01')
//.
//. > S.max ('10') ('2')
//. '2'
//. ```
_.max = {
consts: {a: [Z.Ord]},
types: [a, a, a],
impl: curry2 (Z.max)
};
//# clamp :: Ord a => a -> a -> a -> a
//.
//. Takes a lower bound, an upper bound, and a value of the same type.
//. Returns the value if it is within the bounds; the nearer bound otherwise.
//.
//. See also [`min`](#min) and [`max`](#max).
//.
//. ```javascript
//. > S.clamp (0) (100) (42)
//. 42
//.
//. > S.clamp (0) (100) (-1)
//. 0
//.
//. > S.clamp ('A') ('Z') ('~')
//. 'Z'
//. ```
_.clamp = {
consts: {a: [Z.Ord]},
types: [a, a, a, a],
impl: curry3 (Z.clamp)
};
//# id :: Category c => TypeRep c -> c
//.
//. [Type-safe][sanctuary-def] version of [`Z.id`][].
//.
//. ```javascript
//. > S.id (Function) (42)
//. 42
//. ```
_.id = {
consts: {c: [Z.Category]},
types: [TypeRep (c), c],
impl: Z.id
};
//# concat :: Semigroup a => a -> a -> a
//.
//. Curried version of [`Z.concat`][].
//.
//. ```javascript
//. > S.concat ('abc') ('def')
//. 'abcdef'
//.
//. > S.concat ([1, 2, 3]) ([4, 5, 6])
//. [1, 2, 3, 4, 5, 6]
//.
//. > S.concat ({x: 1, y: 2}) ({y: 3, z: 4})
//. {x: 1, y: 3, z: 4}
//.
//. > S.concat (S.Just ([1, 2, 3])) (S.Just ([4, 5, 6]))
//. Just ([1, 2, 3, 4, 5, 6])
//.
//. > S.concat (Sum (18)) (Sum (24))
//. Sum (42)
//. ```
_.concat = {
consts: {a: [Z.Semigroup]},
types: [a, a, a],
impl: curry2 (Z.concat)
};
//# empty :: Monoid a => TypeRep a -> a
//.
//. [Type-safe][sanctuary-def] version of [`Z.empty`][].
//.
//. ```javascript
//. > S.empty (String)
//. ''
//.
//. > S.empty (Array)
//. []
//.
//. > S.empty (Object)
//. {}
//.
//. > S.empty (Sum)
//. Sum (0)
//. ```
_.empty = {
consts: {a: [Z.Monoid]},
types: [TypeRep (a), a],
impl: Z.empty
};
//# invert :: Group g => g -> g
//.
//. [Type-safe][sanctuary-def] version of [`Z.invert`][].
//.
//. ```javascript
//. > S.invert (Sum (5))
//. Sum (-5)
//. ```
_.invert = {
consts: {g: [Z.Group]},
types: [g, g],
impl: Z.invert
};
//# filter :: Filterable f => (a -> Boolean) -> f a -> f a
//.
//. Curried version of [`Z.filter`][]. Discards every element that does not
//. satisfy the predicate.
//.
//. See also [`reject`](#reject).
//.
//. ```javascript
//. > S.filter (S.odd) ([1, 2, 3])
//. [1, 3]
//.
//. > S.filter (S.odd) ({x: 1, y: 2, z: 3})
//. {x: 1, z: 3}
//.
//. > S.filter (S.odd) (S.Nothing)
//. Nothing
//.
//. > S.filter (S.odd) (S.Just (0))
//. Nothing
//.
//. > S.filter (S.odd) (S.Just (1))
//. Just (1)
//. ```
function filter(pred) {
return function(filterable) {
return Z.filter (pred, filterable);
};
}
_.filter = {
consts: {f: [Z.Filterable]},
types: [$.Predicate (a), f (a), f (a)],
impl: filter
};
//# reject :: Filterable f => (a -> Boolean) -> f a -> f a
//.