forked from jtobey/javascript-bignum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathschemeNumber.js
6558 lines (5508 loc) · 230 KB
/
schemeNumber.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
// Scheme numerical tower in JavaScript.
// Copyright (c) 2011,2012 by John Tobey <[email protected]>
/*
File: schemeNumber.js
Exports:
<SchemeNumber>
Depends:
<biginteger.js> for <BigInteger>
*/
/*
Class: SchemeNumber
A number object as <defined by the Scheme language at
http://www.r6rs.org/>.
Scheme supports *exact* arithmetic and mixing exact with standard
(*inexact*) numbers. Several basic operations, including
addition, subtraction, multiplication, and division, when given
only exact arguments, must return an exact, numerically correct
result.
These operations are allowed to fail due to running out of memory,
but they are not allowed to return approximations the way
ECMAScript operators may, unless given one or more inexact
arguments.
For example, adding exact *1/100* to exact *0* one hundred times
produces exactly *1*, not 1.0000000000000007 as in JavaScript.
Raising exact *2* to the power of exact *1024* returns a 308-digit
integer with complete precision, not *Infinity* as in ECMAScript.
This implementation provides all functions listed in the <R6RS
Scheme specification at http://www.r6rs.org/>, Section 11.7, along
with <eqv?> from Section 11.5. (<eqv?> uses JavaScript's *===* to
compare non-numbers.)
Exact numbers support the standard ECMA Number formatting methods
(toFixed, toExponential, and toPrecision) without a fixed upper
limit to precision.
The schemeNumber.js file exports an object <SchemeNumber>. It
contains a property <fn>, which in turn contains the functions
implementing the numeric types.
The <SchemeNumber> object is in fact a function that converts its
argument to a Scheme number: similar to a constructor, but it may
not always return an object, let alone a unique object.
Parameters:
obj - Object to be converted to a Scheme number.
*obj* may have any of the following
types:
Scheme number - returned unchanged.
String - converted as if by *string->number*.
Native ECMAScript number - treated as an inexact real.
Returns:
A Scheme number.
Exceptions:
If *obj* can not be parsed, <SchemeNumber> will <raise> an
exception with condition type *&assertion*.
See Also:
<fn>, <raise>, <R6RS Chapter 3: Numbers at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-6.html#node_chap_3>
*/
var SchemeNumber = (function() {
//
// Multiple dispatch support.
//
var DispatchJs = (function() {
"use strict";
/*
Multiple dispatch for JavaScript functions of fixed arity. Example:
// B and C inherit from A. D inherits from C.
var A = disp.defClass("A", {ctor: function(x) { this.x = x }});
var B = disp.defClass("B", {base: "A"});
var C = disp.defClass("C", {base: "A"});
// Classes may be defined after their superclass methods.
//var D = disp.defClass("D", {base: "C"});
// Or you can declare existing classes:
//var disp = DispatchJs;
//function A(){} A.prototype = {};
//disp.defClass("A", {ctor: A});
//function B(){} B.prototype = new A();
//disp.defClass("B", {ctor: B, base "A"});
//function C(){} C.prototype = new A();
//disp.defClass("C", {ctor: C, base "A"});
//function D(){} D.prototype = new C();
//disp.defClass("D", {ctor: D, base "C"});
// This creates a function of 2 arguments:
var frob = disp.defGeneric("frob", 2);
// Define methods. Methods receive frob's first argument as "this" and
// the rest as method arguments.
frob.def("A", "A", function(a1) { return "A A" });
frob.def("A", "B", function(a1) { return "A B" });
frob.def("B", "A", function(a1) { return "B A" });
frob.def("B", "B", function(a1) { return "B B" });
frob.def("A", "C", function(a1) { return "A C" });
var D = disp.defClass("D", function(x) { this.x = x }, "C");
frob.def("D", "D", function(a1) { return "D D" });
// Create some arguments:
var a = new A();
var b = new B();
var c = new C();
var d = new D();
// Call the function:
frob(a,a); // "A A"
frob(a,b); // "A B"
frob(a,c); // "A C"
frob(a,d); // "A C"
frob(b,a); // "B A"
frob(b,b); // "B B"
frob(b,c); // "B A" or "A C"
frob(b,d); // "B A" or "A C"
frob(c,a); // "A A"
frob(c,b); // "A B"
frob(c,c); // "A C"
frob(c,d); // "A C"
frob(d,a); // "A A"
frob(d,b); // "A B"
frob(d,c); // "A C"
frob(d,d); // "D D"
Ambiguous calls such as frob(b,c) and frob(b,d) above use whichever of
the best candidates was defined first: the method for types B,A or the
one for A,C.
*/
function short_fn(f) {
return String(f).replace(/(?:.|\n)*(function .*?\(.*?\))(?:.|\n)*/, "$1");
}
var Formals = [];
function makeContext(opts) {
var g = opts.globals;
var _Function = (g ? g.Function : Function);
var uncurry = _Function.prototype.bind.bind(_Function.prototype.call);
var _Object = (g ? g.Object : Object);
var _String = (g ? g.String : String);
var _Array = (g ? g.Array : Array);
var _Error = (g ? g.Error : Error);
var _apply = uncurry(_Function.prototype.apply);
var _slice = uncurry(_Array.prototype.slice);
var _join = uncurry(_Array.prototype.join);
var _push = uncurry(_Array.prototype.push);
var _unshift = uncurry(_Array.prototype.unshift);
var _forEach = uncurry(_Array.prototype.forEach);
var _concat = uncurry(_Array.prototype.concat);
var _replace = uncurry(_String.prototype.replace);
var _split = uncurry(_String.prototype.split);
var _create = _Object.create;
var _hasOwnProperty = uncurry(_Object.prototype.hasOwnProperty);
var String_indexOf = uncurry(_String.prototype.indexOf);
var Array_indexOf = uncurry(_Array.prototype.indexOf);
var prefix = opts.methodNamePrefix || "_jsmd";
var ePrefix = _replace(prefix, /([\"\\])/g, "\\$1");
var sep = opts.methodNameSeparator || " ";
var classes = _create(null);
function classToName(cl) {
if (cl != null) {
var name = cl[prefix];
if (typeof name === "string")
if (classes[name] && classes[name].ctor === cl)
return name;
else
for (name in classes)
if (classes[name] && classes[name].ctor === cl)
return name;
}
}
function assertClassToName(cl) {
if ("string" === typeof cl)
return cl;
var ret = classToName(cl);
if (ret)
return ret;
throw _Error("Class not defined: " + cl);
}
function pureVirtual() {
var msg = "Abstract method not overridden for ";
try {
msg += this;
}
catch (e) {
try {
msg += _Object.prototype.toString.call(this);
}
catch (e) {
msg += "object";
}
}
throw new _Error(msg);
}
var ret = {
getConstructor: function(name) {
return classes[name] && classes[name].ctor;
},
defClass: function(name, opts) {
var ctor, base;
var bctor, proto, key, sub, sepBase, cname, c;
var ometh, meth, func, array, doit, i, indices;
opts.debug && console.log("defClass: ", name);
if (opts) {
ctor = opts.ctor;
if (opts.base)
base = assertClassToName(opts.base);
}
if (typeof base === "undefined" && ctor && ctor.prototype != null) {
base = classToName(ctor.prototype.constructor);
}
//opts.debug && console.log("base:", base);
if (typeof base !== "undefined") {
bctor = classes[base].ctor;
}
ctor = ctor || function(){}
if (typeof name !== "string") {
throw _Error("Usage: defClass(NAME, [OPTS])");
}
if (classes[name]) {
if (classes[name].ctor !== ctor || classes[name].base !== base)
{
throw _Error("Can't redefine class " + name);
}
return ctor;
}
if (String_indexOf(name, sep) != -1) {
throw _Error((sep == " " ? "Space" : "Separator") +
" in class name: " + name);
}
if (typeof (ctor[prefix]) !== "undefined") {
if (ctor[prefix] !== name)
throw _Error("Cannot define constructor as " + name +
", it was previously defined as " +
ctor[prefix]);
}
else {
ctor[prefix] = name;
}
//opts.debug && console.log("checking prototype constructor");
if (ctor.prototype) {
if (_hasOwnProperty(ctor.prototype, "constructor")) {
if (ctor.prototype.constructor !== ctor)
throw _Error("ctor.prototype.constructor is not ctor");
}
else {
ctor.prototype.constructor = ctor;
}
}
//opts.debug && console.log("ok")
if (!ctor.prototype ||
(bctor && !(ctor.prototype instanceof bctor)))
{
proto = (bctor ? new bctor() : _create(null));
//opts.debug && console.log("proto.constructor[prefix]", proto.constructor[prefix]);
if (ctor.prototype) {
// XXX Used for BigInteger; too hacky?
for (key in ctor.prototype) {
proto[key] = ctor.prototype[key];
}
}
proto.constructor = ctor;
ctor.prototype = proto;
}
classes[name] = {
ctor: ctor,
base: base,
sub: [],
ename: _replace(sep + name, /([\"\\])/g, "\\$1")
};
//opts.debug && console.log("defClass:", name, "base:", base);
if (typeof base !== "undefined") {
sub = classes[base].sub;
if (Array_indexOf(sub, name) === -1)
_push(sub, name);
sepBase = sep + base;
for (cname in classes) {
proto = classes[cname].ctor.prototype;
for (ometh in proto) {
if (!_hasOwnProperty(proto, ometh))
continue;
if (!String_indexOf(ometh, sepBase))
continue;
array = _split(ometh, sep);
if (array[0] !== prefix)
continue;
func = proto[ometh];
indices = [];
for (i = Array_indexOf(array, base, 2); i !== -1;
i = Array_indexOf(array, base, i + 1)) {
_push(indices, i);
}
doit = function(i) {
if (i === indices.length) {
meth = _join(array, sep);
if (meth !== ometh) {
opts.debug && console.log(cname + '["'+meth+'"] propagated -> ' + short_fn(func));
proto[meth] = func;
}
return;
}
array[indices[i]] = base;
doit(i + 1);
array[indices[i]] = name;
doit(i + 1);
}
doit(0);
}
}
}
return ctor;
},
defGeneric: function (fnName, ndisp, nargs) {
if (String_indexOf(fnName, sep) != -1)
throw _Error((sep == " " ? "Space" : "Separator") +
" in function name: " + fnName);
nargs = nargs || ndisp;
if (fnName == ""
|| ndisp < 1 || ndisp != (ndisp | 0)
|| nargs < 1 || nargs != (nargs | 0))
throw Error("Usage: defGeneric(NAME, NDISP [, NARGS])");
var eName = _replace(sep + fnName, /([\"\\])/g, "\\$1");
var eTopMethod = ePrefix + eName;
for (var i = Formals.length; i < nargs; i++)
Formals[i] = "a" + i;
var array = _slice(Formals, 0, nargs);
// e.g., function(a0,a1,a2,a3){return a3["_jsmd frob"](a0,a1,a2)}
_push(array,
"return " + Formals[ndisp-1] + '["' + eTopMethod + '"](' +
_join(_concat(_slice(array, 0, ndisp-1),
_slice(array, ndisp, nargs)), ",") + ')')
var ret = _apply(_Function, null, array);
var func_cache = _create(null);
function get_func(i, etypes) {
var suffix = _join(_slice(etypes, i), "");
if (!func_cache[suffix]) {
var method = ePrefix + eName + suffix;
var array = _concat(_slice(Formals, 0,i),
_slice(Formals, i+1, nargs));
_push(array, "return " + Formals[i-1] +
'["' + method + '"](' +
_join(_concat(_slice(Formals, 0, i-1), "this",
_slice(Formals, i+1, nargs)), ",") +
')');
func_cache[suffix] = _apply(_Function, null, array);
}
return func_cache[suffix];
}
// For error message.
function usageArgs() {
switch (ndisp) {
case 1: return "TYPE";
case 2: return "TYPE1, TYPE2";
case 3: return "TYPE1, TYPE2, TYPE3";
default: return "TYPE1, ..., TYPE" + ndisp;
}
}
// def(TYPE1, ..., TYPEn, FUNCTION)
// Defines FUNCTION as this method's specialization for the
// given types. Each TYPEi must have been passed as the
// NAME argument in a successful call to defClass.
function def() {
var fn = arguments[ndisp] || pureVirtual;
if (typeof fn !== "function") {
throw _Error("Not a function. Usage: " + fnName +
".def(" + usageArgs() + ", FUNCTION)");
}
var types = _slice(arguments, 0, ndisp);
//opts.debug && console.log("def", fnName, types, short_fn(fn));
for (i = 0; i < ndisp; i++) {
// Throw error if not registered.
// XXX Could add def() arguments to a list to be
// defined during defClass.
types[i] = assertClassToName(types[i]);
}
//opts.debug && console.log("def");
do_def(types, fn, _create(null));
}
function do_def(types, fn, inherited) {
var cs = new _Array(ndisp);
var eTypes = new _Array(ndisp);
var i, suffix, oldm, newm;
for (i = 0; i < ndisp; i++) {
cs[i] = classes[types[i]];
//opts.debug && console.log("cs[" + i + "]=classes[", types[i], "]");
eTypes[i] = cs[i].ename;
}
opts.debug && console.log("do_def", fnName, eTypes);
oldm = new Array(ndisp);
for (i = ndisp-1, suffix = ""; ; i--) {
oldm[i] = cs[i].ctor.prototype[
prefix + sep + fnName + suffix];
//opts.debug && console.log("oldm[" + i + "]" + oldm[i]);
if (i === 0)
break;
suffix = eTypes[i] + suffix;
}
newm = new _Array(ndisp);
newm[0] = fn;
for (i=1; i<ndisp; i++)
newm[i] = get_func(i, eTypes);
function doit(i, method) {
var key;
var proto = cs[i].ctor.prototype;
if (proto[method] && proto[method] !== oldm[i]) {
opts.debug && console.log("Skipping " + i + " " + types[i] + '["' + method + '"] ' + short_fn(proto[method]) + "!=" + short_fn(oldm[i]));
return; // already more specialized in an argument.
}
//console.log("doit("+i+","+method+") "+cs[i].ename);
if (proto === Object.prototype) // sanity check.
throw Error("BUG: code would modify Object.prototype.");
if (proto[method] !== newm[i]) {
key = types[i] + sep + method;
if ((key in inherited) && newm[i] === inherited[key]) {
opts.debug && console.log(eTypes[i] + '["'+method+'"] ' + short_fn(proto[method]) + " -> DELETED");
delete(proto[method]);
}
else {
opts.debug && console.log(eTypes[i] + '["'+method+'"] ' + short_fn(proto[method]) + " -> " + short_fn(newm[i]));
if (!_hasOwnProperty(proto, method)) {
inherited[key] = proto[method];
}
proto[method] = newm[i];
}
}
if (i === 0)
return;
function doit2(k) {
doit(i - 1, method + sep + k);
_forEach(classes[k].sub, doit2);
}
doit2(types[i]);
}
doit(ndisp-1, prefix + sep + fnName);
}
ret.def = def;
return ret;
}
// lookup: TO DO
};
if (opts.debug)
ret.classes = classes;
return ret;
}
var ret = makeContext(Object.create(null));
ret.makeContext = makeContext;
return ret;
})();
//if (typeof exports !== "undefined") {
// exports.DispatchJs = DispatchJs;
// exports.makeContext = DispatchJs.makeContext;
// exports.defClass = DispatchJs.defClass;
// exports.defGeneric = DispatchJs.defGeneric;
//}
/*
Constructor: PluginContainer(plugins)
A PluginContainer is just a set of properties, referred to as
"plugins", with an interface to change them and subscribe to
notification of such changes.
If *plugins* is passed, it is stored as if via <extend> as the
initial set of plugins.
*/
function PluginContainer(init) {
"use strict";
// XXX use of globals via Array and Function methods, Object,
// Error, and undefined: should virtualize.
if (!(this instanceof PluginContainer))
throw Error("Usage: new PluginContainer()");
var t = this, listeners = [], plugins = Object.create(null);
function mergeChanges(from, to, changed) {
var ret = false;
for (var i in from) {
if (to[i] !== undefined && to[i] !== from[i])
throw Error("Conflicting changes to " + i);
if (changed)
changed[i] = from[i];
to[i] = from[i];
ret = true;
}
return ret;
}
/*
Property: onChange
Event used to publish changes to plugins.
> plugins.onChange.subscribe(listener);
After <extend> changes one or more plugin values, it calls
*listener* with two arguments: the <PluginContainer> and an object
whose properties are the changed plugins.
No call results from passing <extend> an empty object or one whose
values all equal the current corresponding plugins.
> plugins.onChange.unsubscribe(listener);
Reverses the effect of an earlier *subscribe* call.
*/
var onChange = {
fire: function(changes) {
function notify(listener) {
listener.call(listener, t, changes);
}
listeners.forEach(notify);
},
subscribe: function(listener) {
listeners.push(listener);
},
unsubscribe: function(listener) {
function isNotIt(l) { return l !== listener; }
listeners = listeners.filter(isNotIt);
}
};
t.onChange = onChange;
/*
Method: extend(newPlugins)
Adds or replaces plugins in the container.
*newPlugins* must be an object. All of its properties
(technically, its own, enumerable properties) are stored as new or
replacement plugins. If this results in any actual changes, all
of the container's <onChange> listeners are notified.
Method: extend(name1, plugin1, name2, plugin2, ...)
Like extend({ *name1* : *plugin1*, *name2* : *plugin2*, ... })
*/
t.extend = function() {
var changes = Object.create(null);
var newPlugins = arguments[0], i;
if (typeof newPlugins !== "object") {
if (arguments.length & 1)
throw Error("extend: Wrong argument types");
newPlugins = Object.create(null);
for (i = 0; i < arguments.length; i += 2) {
if (arguments[i] in newPlugins)
throw Error("extend: " + arguments[i] +
" given more than once");
newPlugins[arguments[i]] = arguments[i+1];
}
}
if (mergeChanges(newPlugins, plugins, changes))
onChange.fire(changes);
};
/*
Method: get(pluginName)
Returns the plugin named *pluginName*, or *undefined* if none
exists by that name.
*/
t.get = function(pluginName) {
return plugins[pluginName];
};
t.list = function() {
return Object.keys(plugins);
};
if (init) {
t.extend(init);
}
}
//
// Uncomment "assert(...)" to use this:
//
function assert(x) { if (!x) throw new Error("assertion failed"); }
function getEs5Globals() {
// Package the ECMAScript 5 Global Object properties so that
// careful users can provide a safer-seeming copy of them. XXX If
// you want to use this, consider auditing PluginContainer and
// JsDispatch, too.
return {
NaN : NaN,
Infinity : Infinity,
undefined : undefined,
eval : eval,
parseInt : parseInt,
parseFloat : parseFloat,
isNaN : isNaN,
isFinite : isFinite,
decodeURI : decodeURI,
decodeURIComponent : decodeURIComponent,
encodeURI : encodeURI,
encodeURIComponent : encodeURIComponent,
Object : Object,
Function : Function,
Array : Array,
String : String,
Boolean : Boolean,
Number : Number,
Date : Date,
RegExp : RegExp,
Error : Error,
EvalError : EvalError,
RangeError : RangeError,
ReferenceError : ReferenceError,
SyntaxError : SyntaxError,
TypeError : TypeError,
URIError : URIError,
Math : Math,
JSON : JSON
};
}
function implementUncurry(plugins) {
var g = plugins.get("es5globals");
var api = g.Object.create(null);
/*
uncurry(func) returns a function equivalent to
> function(arg...) { return func.call(arg...); }
but not relying on func or its prototype having a "call"
property. The point is to make library code behave the same
after arbitrary code runs, possibly improving security and
performance.
http://wiki.ecmascript.org/doku.php?id=conventions:safe_meta_programming
*/
api.uncurry = g.Function.prototype.bind.bind(g.Function.prototype.call);
return api;
}
/*
Function: defineGenericFunctions(plugins)
Creates the generic functions of number subtypes called by
higher-level library code.
The bulk of the internal/plugin API consists of these functions.
Their interfaces are optimized for ease of implementation and for
use in implementing the library. By contrast, the Scheme library
strives more for interface stability and convenience of use.
For example, the public subtraction function, <fn["-"]>, accepts
one or more arguments, converts them from native types if
necessary, and subtracts all but the first from the first, unless
there is only one, in which case it negates it. The library
converts all that into calls to <subtract>, with exactly two
arguments, both guaranteed to be Scheme numbers, or <negate> as
the case may be.
Input:
*plugins* shall be a <PluginContainer> containing *Dispatch*, a
<JsDispatch> object. <defineGenericFunctions> calls the
*defGeneric* method of *Dispatch* to create each generic function.
Functions:
toSchemeNumber - see <implementSchemeNumber>
numberToString - generic function(schemeNumber, radix, precision)
Equivalent to <fn["number->string"]> but with *radix* and
*precision* as native numbers.
isExact - generic function(schemeNumber)
"exact?"
isInexact - generic function(schemeNumber)
"inexact?"
isComplex - generic function(schemeNumber)
"complex?"
isReal - generic function(schemeNumber)
"real?"
isRational - generic function(schemeNumber)
"rational?"
isInteger - generic function(schemeNumber)
"integer?"
isZero - generic function(schemeNumber)
"zero?"
toExact - generic function(schemeNumber)
"exact"
toInexact - generic function(schemeNumber)
"inexact"
negate - generic function(schemeNumber)
Returns the argument's additive inverse, -*schemeNumber*.
reciprocal - generic function(schemeNumber)
Return the argument's multiplicative inverse, 1 / *schemeNumber*.
eq - generic function(schemeNumber, schemeNumber)
"="
ne - generic function(schemeNumber, schemeNumber)
Returns true if, and only if, the arguments are *not* equal in the
sense of Scheme's "=".
add - generic function(schemeNumber, schemeNumber)
Returns the sum of the two arguments.
subtract - generic function(schemeNumber1, schemeNumber2)
Returns the difference *schemeNumber1* - *schemeNumber2*.
multiply - generic function(schemeNumber, schemeNumber)
Returns the product of the two arguments.
divide - generic function(schemeNumber1, schemeNumber2)
Returns the quotient *schemeNumber1* / *schemeNumber2*.
square - generic function(schemeNumber)
Returns the argument's square.
realPart - generic function(complex)
"real-part"
imagPart - generic function(complex)
"imag-part"
expt - generic function(schemeNumber, integer)
As in Scheme.
expt - generic function(complex, complex)
As in Scheme.
exp - generic function(complex)
As in Scheme.
magnitude - generic function(complex)
As in Scheme.
angle - generic function(complex)
As in Scheme.
sqrt - generic function(complex)
As in Scheme.
log - generic function(complex)
Single-argument *log* as in Scheme.
asin - generic function(complex)
As in Scheme.
acos - generic function(complex)
As in Scheme.
atan - generic function(complex)
Single-argument *atan* as in Scheme.
sin - generic function(complex)
As in Scheme.
cos - generic function(complex)
As in Scheme.
tan - generic function(complex)
As in Scheme.
SN_isFinite - generic function(real)
"finite?"
SN_isInfinite - generic function(real)
"infinite?"
SN_isNaN - generic function(real)
"nan?"
isUnit - generic function(real)
Returns true if its argument equals 1 or -1.
abs - generic function(real)
As in Scheme.
isPositive - generic function(real)
"positive?"
isNegative - generic function(real)
"negative?"
sign - generic function(real)
Returns native -1 if *real* is negative, 0 if zero, or 1 if positive.
floor - generic function(real)
As in Scheme.
ceiling - generic function(real)
As in Scheme.
truncate - generic function(real)
As in Scheme.
round - generic function(real)
As in Scheme.
compare - generic function(real1, real2)
Returns the <sign> of the difference <real1 - real2>.
gt - generic function(real, real)
">"
lt - generic function(real, real)
"<"
ge - generic function(real, real)
">="
le - generic function(real, real)
"<="
divAndMod - generic function(real, real)
"div-and-mod"
div - generic function(real, real)
As in Scheme.
mod - generic function(real, real)
As in Scheme.
atan2 - generic function(real, real)
Equivalent to *atan* with two arguments in Scheme.
numerator - generic function(rational)
As in Scheme.
denominator - generic function(rational)
As in Scheme.
isEven - generic function(exactInteger)
"even?"
isOdd - generic function(exactInteger)
"odd?"
exp10 - generic function(significand, exponent)
Both arguments are exact integers. Returns an exact integer equal
to the *significand* times ten to the *exponent*.
gcdNonnegative - generic function(exactInteger, exactInteger)
Both arguments are non-negative, exact integers. <gcdNonnegative>
returns their greatest common divisor (GCD).
divideReduced - generic function(numerator, denominator)
Both arguments are exact, relatively prime integers, and
*denominator* is greater than zero. <divideReduced> returns an
exact rational equal to *numerator* divided by *denominator*.
*/
function defineGenericFunctions(plugins) {
"use strict";
var g = plugins.get("es5globals");
var disp = plugins.get("Dispatch");
var api = g.Object.create(null);
function def(name, ndisp, nargs) {
api[name] = disp.defGeneric(name, ndisp, nargs);
}
def("toSchemeNumber", 1);
def("numberToString", 1, 3); // 2nd and 3rd args native
def("isExact", 1);
def("isInexact", 1);
def("isComplex", 1);
def("isReal", 1);
def("isRational", 1);
def("isInteger", 1);
def("isZero", 1);
def("toExact", 1);
def("toInexact", 1);
def("negate", 1);
def("reciprocal", 1);
def("eq", 2);
def("ne", 2);
def("add", 2);
def("subtract", 2);
def("multiply", 2);
def("divide", 2);
def("square", 1);
def("realPart", 1);
def("imagPart", 1);
def("magnitude", 1);
def("angle", 1);
def("conjugate", 1);
def("expt", 2);
def("exp", 1);
def("sqrt", 1);
def("log", 1);
def("asin", 1);
def("acos", 1);
def("atan", 1);
def("sin", 1);
def("cos", 1);
def("tan", 1);
def("SN_isFinite", 1);
def("SN_isInfinite", 1);
def("SN_isNaN", 1);
def("isUnit", 1);
def("abs", 1);
def("isPositive", 1);
def("isNegative", 1);
def("sign", 1);
def("floor", 1);
def("ceiling", 1);
def("truncate", 1);
def("round", 1);
def("compare", 2);
def("gt", 2);
def("lt", 2);
def("ge", 2);
def("le", 2);
def("divAndMod", 2);
def("div", 2);
def("mod", 2);
def("atan2", 2);
def("numerator", 1);
def("denominator", 1);
def("numeratorAndDenominator", 1);
def("isEven", 1);
def("isOdd", 1);
def("exactIntegerSqrt", 1);
def("exp10", 1, 2); // 2nd arg exact integer
def("gcdNonnegative", 2);
def("divideReduced", 2);
def("bitwiseNot", 1);
def("bitwiseAnd", 2);
def("bitwiseIor", 2);
def("bitwiseXor", 2);
def("bitCount", 1);
def("bitLength", 1);