<NME> schemeNumber.js <BEF> // Scheme numerical tower in JavaScript. // Copyright (c) 2011,2012 by John Tobey <jtobey@john-edwin-tobey.org> /* 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); def("firstBitSet", 1); def("isBitSet", 1, 2); // 2nd arg convertible to index def("copyBit", 1, 3); // 2nd arg convertible to index; 3rd arg boolean def("bitField", 1, 3); def("copyBitField", 2, 4); def("bitShift", 1, 2); def("rotateBitField", 1, 4); def("reverseBitField", 1, 3); return api; } function defineSchemeNumberType(plugins) { "use strict"; var g = plugins.get("es5globals"); var _NaN = g.NaN; var api = g.Object.create(null); var numberToString = plugins.get("numberToString"); var disp = plugins.get("Dispatch"); function SchemeNumberType(){} // Inherit from Number so that "x instanceof Number" holds. // But then override the standard methods, which are compatible // only with native Number objects. SchemeNumberType.prototype = new Number(); // Good defaults. function genericToString(radix) { if (numberToString) return numberToString(this, radix); return "[object SchemeNumber]"; } function genericToLocaleString() { return genericToString(); } function retNaN() { return _NaN; } // Bad default. function genericFormatter() { if (numberToString) return numberToString(this); return "SchemeNumber"; } SchemeNumberType.prototype.toFixed = genericFormatter; SchemeNumberType.prototype.toExponential = genericFormatter; SchemeNumberType.prototype.toPrecision = genericFormatter; SchemeNumberType.prototype.toString = genericToString; SchemeNumberType.prototype.toLocaleString = genericToLocaleString; SchemeNumberType.prototype.valueOf = retNaN; disp.defClass("SchemeNumber", { ctor: SchemeNumberType }); api.SchemeNumberType = SchemeNumberType; return api; } /* Function: defineDebugFunction(plugins) Creates a generic function, *debug*, for inspecting number objects. Input: *plugins* shall be a <PluginContainer> containing the following element. Dispatch - a <JsDispatch> object. <defineDebugFunction> calls the *Dispatch* object's *defGeneric* method to create the *debug* function, and calls the resulting function's *def* method with class name "SchemeNumber" to define a generic implementation of *debug*. Output: debug - generic function(schemeNumber) -> string Applications must not rely on the returned string's format. Number implementations should specialize this function to provide internal details of use during development. Developers may obtain this function via *SchemeNumber.plugins.get("debug")*. Example: > SchemeNumber.plugins.get("debug")(SchemeNumber(10)) // "EINative(10)" See Also: <JsDispatch> */ function defineDebugFunction(plugins) { "use strict"; var g = plugins.get("es5globals"); var uncurry = plugins.get("uncurry"); var disp = plugins.get("Dispatch"); var SchemeNumberType = plugins.get("SchemeNumberType"); var Object_toString = uncurry(g.Object.prototype.toString); var api = g.Object.create(null); // Generic default for classes that don't specialize debug. function SchemeNumber_debug() { var t; try { t = this.toString(); } catch (e) { try { t = Object_toString(this); } catch (e) { t = "?"; } } return "SchemeNumber(" + t + ")"; } api.debug = disp.defGeneric("debug", 1); api.debug.def(SchemeNumberType, SchemeNumber_debug); return api; } /* Function: implementCoreLibrary(plugins) Creates the plugins required by Scheme functions and a few others. Input: *plugins* shall be a <PluginContainer> containing the items listed below. All may be added after the call to <implementCoreLibrary> but before any use of its results. When changes to plugins produce changes in non-function results (such as *ZERO* and *ONE*), the library broadcasts the changes via the <PluginContainer.onChange> event. SchemeNumber - function(any) The <SchemeNumber> object as returned by <implementSchemeNumber(plugins)>. nativeToExactInteger - function(integer) *integer* is a native ECMAScript number of integer value. <nativeToExactInteger> returns an exact Scheme number whose value equals *integer*. nativeToInexact - function(number) *number* is a native ECMAScript number, possibly infinite or *NaN*. <nativeToInexact> returns an inexact Scheme number approximating its argument. parseExactInteger - function(sign, string, radix) *sign* is the native number 1 or -1. *radix* is the native number 2, 8, 10, or 16. <parseExactInteger> must be a function returning a Scheme number equal to *sign* times the result of parsing *string* as a positive, unprefixed, exact integer in the given radix. parseInexact - function(sign, string) *sign* is the native number 1 or -1. <parseExact> must be a function returning a Scheme number equal to *sign* times the result of parsing *string* as a positive, unprefixed, decimal, inexact, real number. exactRectangular - function(x, y) *x* and *y* are exact reals, *y* non-zero. <exactRectangular> returns an exact complex equal to *x* + (i * *y*). inexactRectangular - function(x, y) *x* and *y* are inexact reals. <inexactRectangular> returns an inexact complex equal to *x* + (i * *y*). exactPolar - function(r, theta) *r* and *theta* are exact reals. <exactPolar> returns an exact complex equal to *r* * exp(i * *theta*). inexactPolar - function(r, theta) *r* and *theta* are inexact reals. <inexactPolar> returns an inexact complex equal to *r* * exp(i * *theta*). Output: <implementCoreLibrary> returns an object with the following properties. ZERO - the exact integer *0*. ONE - the exact integer *1*. TWO - the exact integer *2*. MINUS_ONE - the exact integer *-1*. INEXACT_ZERO - the inexact integer *0.0*. INEXACT_ONE - the inexact integer *1.0*. PI - the inexact real number pi. INFINITY - the inexact real number *+inf.0*. MINUS_INFINITY - the inexact real number *-inf.0*. NAN - the inexact real number *+nan.0*. I - the exact complex unit *i*. MINUS_I - the exact complex unit *-i*. raise - function(conditionType, message, irritant...) This *raise* simply calls the user-overridable <SchemeNumber.raise> but enforces the contract not to return. defaultRaise - function(conditionType, message, irritant...) Throws an Error describing the arguments. raiseDivisionByExactZero - function() Raises an exception as specified by Scheme to report division by exact zero. isNumber - function(x) Returns true if *x* is a Scheme number. assertReal - function(x) Returns *x* if *x* is a real Scheme number, otherwise raises an exception as specified by Scheme for invalid argument type. toReal - function(x) Converts *x* to a Scheme number and behaves as if by returning *assertReal(x)*. assertInteger - function(x) Returns *x* if *x* is a Scheme integer, otherwise raises an exception as specified by Scheme for invalid argument type. toInteger - function(x) Converts *x* to a Scheme number and behaves as if by returning *assertInteger(x)*. assertExact - function(x) Returns *x* if *x* is an exact Scheme number, otherwise raises an exception as specified by Scheme for invalid argument type. stringToNumber - function(string, radix, exact) <stringToNumber> returns the Scheme number whose external representation is *string* with added prefixes corresponding to either or both of *radix* and *exact*, if defined. *s* should be the external representation of a Scheme number, such as "2/3" or "#e1.1@-2d19". If *s* does not represent a Scheme number, <stringToNumber> returns *false*. If *radix* is given, it must be either 2, 8, 10, or 16, and *s* must not contain a radix prefix. The function behaves as if *s* did contain the prefix corresponding to *radix*. If *exact* is given, it must have type "boolean", and *s* must not contain an exactness prefix. The function behaves as if *s* contained the corresponding prefix ("#e" if *exact* is true, "#i" if false). truncateToPrecision - XXX documentation incomplete. */ function implementCoreLibrary(plugins) { "use strict"; // Abstract types, generic functions, and the SchemeNumber object. // XXX Could remove unused items. var SchemeNumber, toSchemeNumber, SchemeNumberType, Complex, Real, InexactReal, ExactReal, ExactRational, ExactInteger, numberToString, isExact, isInexact, isComplex, isReal, isRational, isInteger, isZero, toExact, toInexact, negate, reciprocal, eq, ne, add, subtract, multiply, divide, square, realPart, imagPart, expt, expt, exp, magnitude, angle, sqrt, log, asin, acos, atan, sin, cos, tan, SN_isFinite, SN_isInfinite, SN_isNaN, isUnit, abs, isPositive, isNegative, sign, floor, ceiling, truncate, round, compare, gt, lt, ge, le, divAndMod, div, mod, atan2, numerator, denominator, numeratorAndDenominator, isEven, isOdd, exp10, gcdNonnegative, divideReduced; SchemeNumber = plugins.get("SchemeNumber"); SchemeNumberType = plugins.get("SchemeNumberType"); Complex = plugins.get("Complex"); Real = plugins.get("Real"); InexactReal = plugins.get("InexactReal"); ExactReal = plugins.get("ExactReal"); ExactRational = plugins.get("ExactRational"); ExactInteger = plugins.get("ExactInteger"); toSchemeNumber = plugins.get("toSchemeNumber"); numberToString = plugins.get("numberToString"); isExact = plugins.get("isExact"); isInexact = plugins.get("isInexact"); isComplex = plugins.get("isComplex"); isReal = plugins.get("isReal"); isRational = plugins.get("isRational"); isInteger = plugins.get("isInteger"); isZero = plugins.get("isZero"); toExact = plugins.get("toExact"); toInexact = plugins.get("toInexact"); negate = plugins.get("negate"); reciprocal = plugins.get("reciprocal"); eq = plugins.get("eq"); ne = plugins.get("ne"); add = plugins.get("add"); subtract = plugins.get("subtract"); multiply = plugins.get("multiply"); divide = plugins.get("divide"); square = plugins.get("square"); realPart = plugins.get("realPart"); imagPart = plugins.get("imagPart"); expt = plugins.get("expt"); expt = plugins.get("expt"); exp = plugins.get("exp"); magnitude = plugins.get("magnitude"); angle = plugins.get("angle"); sqrt = plugins.get("sqrt"); log = plugins.get("log"); asin = plugins.get("asin"); acos = plugins.get("acos"); atan = plugins.get("atan"); sin = plugins.get("sin"); cos = plugins.get("cos"); tan = plugins.get("tan"); SN_isFinite = plugins.get("SN_isFinite"); SN_isInfinite = plugins.get("SN_isInfinite"); SN_isNaN = plugins.get("SN_isNaN"); isUnit = plugins.get("isUnit"); abs = plugins.get("abs"); isPositive = plugins.get("isPositive"); isNegative = plugins.get("isNegative"); sign = plugins.get("sign"); floor = plugins.get("floor"); ceiling = plugins.get("ceiling"); truncate = plugins.get("truncate"); round = plugins.get("round"); compare = plugins.get("compare"); gt = plugins.get("gt"); lt = plugins.get("lt"); ge = plugins.get("ge"); le = plugins.get("le"); divAndMod = plugins.get("divAndMod"); div = plugins.get("div"); mod = plugins.get("mod"); atan2 = plugins.get("atan2"); numerator = plugins.get("numerator"); denominator = plugins.get("denominator"); numeratorAndDenominator = plugins.get("numeratorAndDenominator"); isEven = plugins.get("isEven"); isOdd = plugins.get("isOdd"); exp10 = plugins.get("exp10"); gcdNonnegative = plugins.get("gcdNonnegative"); divideReduced = plugins.get("divideReduced"); // Functions to be provided by number implementations. var nativeToInexact, parseInexact; var parseExactInteger, nativeToExactInteger; var divideReducedNotByOne; var exactRectangular, inexactRectangular, exactPolar, inexactPolar; // Constants to be defined here once we have the necessaries. var ZERO, ONE, TWO, MINUS_ONE, I, MINUS_I; var INEXACT_ZERO, INEXACT_ONE, PI, INFINITY, MINUS_INFINITY, NAN; // Imports from ECMAScript. var g = plugins.get("es5globals"); var uncurry = plugins.get("uncurry"); var Array_slice = uncurry(g.Array.prototype.slice); var Array_join = uncurry(g.Array.prototype.join); var Number_toString = uncurry(g.Number.prototype.toString); var String_indexOf = uncurry(g.String.prototype.indexOf); var String_substring = uncurry(g.String.prototype.substring); var String_replace = uncurry(g.String.prototype.replace); var RegExp_test = uncurry(g.RegExp.prototype.test); var Math_LN10 = g.Math.LN10; var Math_LN2 = g.Math.LN2; var Math_PI = g.Math.PI; var Math_abs = g.Math.abs; var Math_floor = g.Math.floor; var Math_pow = g.Math.pow; var _LN2 = g.Math.LN2; var _LN10 = g.Math.LN10; var _PI = g.Math.PI; var _undefined = g.undefined; var _Infinity = g.Infinity; var _NaN = g.NaN; var _parseInt = g.parseInt; var _isNaN = g.isNaN; var _isFinite = g.isFinite; var api = g.Object.create(null); function onPluginsChanged(plugins, changed) { nativeToExactInteger = plugins.get("nativeToExactInteger"); parseExactInteger = plugins.get("parseExactInteger"); nativeToInexact = plugins.get("nativeToInexact"); parseInexact = plugins.get("parseInexact"); divideReducedNotByOne = plugins.get("divideReducedNotByOne"); exactRectangular = plugins.get("exactRectangular"); inexactRectangular = plugins.get("inexactRectangular"); exactPolar = plugins.get("exactPolar"); inexactPolar = plugins.get("inexactPolar"); function getComplexConstant(x, y) { try { return exactRectangular(nativeToExactInteger(x), nativeToExactInteger(y)); } catch (e) { return _undefined; } } var exts = g.Object.create(null); if (changed.nativeToExactInteger || changed.exactRectangular) { I = exts.I = getComplexConstant(0, 1); MINUS_I = exts.MINUS_I = getComplexConstant(0, -1); } if (changed.nativeToExactInteger) { ZERO = exts.ZERO = nativeToExactInteger(0); ONE = exts.ONE = nativeToExactInteger(1); TWO = exts.TWO = nativeToExactInteger(2); MINUS_ONE = exts.MINUS_ONE = nativeToExactInteger(-1); } if (changed.nativeToInexact) { INEXACT_ZERO = exts.INEXACT_ZERO = nativeToInexact(0); INEXACT_ONE = exts.INEXACT_ONE = nativeToInexact(1); PI = exts.PI = nativeToInexact(Math_PI); INFINITY = exts.INFINITY = nativeToInexact(_Infinity); MINUS_INFINITY = exts.MINUS_INFINITY = nativeToInexact(-_Infinity); NAN = exts.NAN = nativeToInexact(_NaN); } // XXX should not recurse into extend(). Should return exts // here and make extend() loop. plugins.extend(exts); } plugins.onChange.subscribe(onPluginsChanged); onPluginsChanged(plugins, {}); function retFalse() { return false; } function retTrue() { return true; } function retThis() { return this; } function retZero() { return ZERO; } function retOne() { return ONE; } function retFirst(a) { return a; } function makeRectangular(x, y) { if (isInexact(x)) return inexactRectangular(x, toInexact(y)); if (isInexact(y)) return inexactRectangular(toInexact(x), y); return exactRectangular(x, y); } function makePolar(x, y) { if (isInexact(x)) return inexactPolar(x, toInexact(y)); if (isInexact(y)) return inexactPolar(toInexact(x), y); return exactPolar(x, y); } function defaultRaise(conditionType, message, irritant) { var i, arg, msg = "SchemeNumber: " + conditionType + ": " + message; if (arguments.length > 2) { msg += ": "; i = 2; while (true) { arg = arguments[i]; try { msg += numberToString(arg); } catch (e) { try { msg += arg; } catch (e) { msg += "?"; } } i++; if (i === arguments.length) break; msg += ", "; } } throw new g.Error(msg); } /* raise - function(conditionType, message, irritants...) Forwards its arguments to <SchemeNumber.raise> and handles errors in that function, namely returning when it shouldn't. */ function raise() { var args = Array_slice(arguments); // Call the exception hook. SchemeNumber.raise.apply(SchemeNumber, args); // Oops, it returned. Fall back to our known good raiser. defaultRaise.apply(this, args); } function raiseDivisionByExactZero() { raise("&assertion", "division by exact zero"); } // // For (rnrs base (6)) i.e. SchemeNumber.fn. Could perhaps move // to a library and get via onPluginsChanged. // // Compute a real that had a |p attached. // See the second half of R6RS Section 4.2.8 and also // http://www.mail-archive.com/r6rs-discuss@lists.r6rs.org/msg01676.html. // This could be greatly optimized for native numbers using // numberToBinary, but I have no use case, so I went with a slow, // (hopefully) correct version. function truncateToPrecision(x, precision, exact) { if (x === false || !isReal(x)) lose(); if (!isZero(x)) { var xabs = abs(x); var shift = precision - Math_floor(log(xabs) / Math_LN2) - 1; var scale = expt(TWO, nativeToExactInteger(Math_abs(shift))); if (shift < 0) scale = reciprocal(scale); var shifted = multiply(xabs, scale); // Correct for log() imprecision. var denom = expt(TWO, nativeToExactInteger(precision)); while (ge(shifted, denom)) { shifted = divide(shifted, TWO); scale = divide(scale, TWO); } for (var twiceShifted = add(shifted, shifted); lt(twiceShifted, denom); twiceShifted = add(shifted, shifted)) { shifted = twiceShifted; scale = add(scale, scale); } // 0.5 <= shifted/denom < 1. var rounded = divide(round(shifted), scale); if (isNegative(x)) rounded = negate(rounded); x = rounded; } // Then make it inexact unless there is #e. if (!exact) x = toInexact(x); return x; } function assertReal(x) { if (!isReal(x)) raise("&assertion", "not a real number", x); return x; } function toReal(x) { x = SchemeNumber(x); isReal(x) || assertReal(x); return x; } function assertRational(q) { if (!isRational(q)) raise("&assertion", "not a rational number", q); return q; } function toRational(q) { q = SchemeNumber(q); isRational(q) || assertRational(q); return q; } function assertInteger(n) { n = SchemeNumber(n); if (!isInteger(n)) raise("&assertion", "not an integer", n); return n; } function toInteger(n) { n = SchemeNumber(n); isInteger(n) || assertInteger(n); return n; } function assertExact(z) { if (isInexact(z)) raise("&assertion", "inexact number", z); return z; } function isNumber(x) { return x instanceof SchemeNumberType; } // // For (rnrs base (6)) i.e. SchemeNumber.fn. // Specifically, fn["string->number"] and SchemeNumber("...") // // How to split a rectangular literal into real and imaginary components: var decimalComplex = /^(.*[^a-zA-Z]|)([-+].*)i$/; var radixComplex = /^(.*)([-+].*)i$/; var nanInfPattern = /^[-+](nan|inf)\.0$/; var exponentMarkerPattern = /[eEsSfFdDlL]/; var decimal10Pattern = /^([0-9]+\.?|[0-9]*\.[0-9]+)([eEsSfFdDlL][-+]?[0-9]+)?$/; var uintegerPattern = { 2: /^[01]+$/, 8: /^[0-7]+$/, 10: /^[0-9]+$/, 16: /^[0-9a-fA-F]+$/ }; var PARSE_ERROR = new g.Object(); function stringToNumber(s, radix, exact) { function lose() { throw PARSE_ERROR; } function check(z) { return z === false ? lose() : z; } function setExact(value) { if (exact !== _undefined) lose(); exact = value; } function setRadix(value) { if (radix) lose(); radix = value; } function parseUinteger(s, sign) { if (!RegExp_test(uintegerPattern[radix], s)) lose(); if (exact === false) { if (radix === 10) return parseInexact(sign, s); return toInexact(parseExactInteger(sign, s, radix)); } return parseExactInteger(sign, s, radix); } function parseReal(s) { if (RegExp_test(nanInfPattern, s)) { if (exact) lose(); switch (s) { case "+inf.0": return INFINITY; case "-inf.0": return MINUS_INFINITY; default: return NAN; } } var sign = 1; switch (s[0]) { case '-': sign = -1; // fall through case '+': s = String_substring(s, 1); } var slash = String_indexOf(s, '/'); if (slash != -1) return divide( parseUinteger(String_substring(s, 0, slash), sign), parseUinteger(String_substring(s, slash + 1), 1)); if (radix !== 10) return parseUinteger(s, sign); var pipe = String_indexOf(s, '|'); if (pipe !== -1) { // WHOA!!! Explicit mantissa width! Somebody really // cares about correctness. However, I haven't got all // day, so execution speed loses. var afterPipe = String_substring(s, pipe + 1); if (!RegExp_test(uintegerPattern[10], afterPipe)) lose(); s = String_substring(s, 0, pipe); var precision = _parseInt(afterPipe, 10); if (precision === 0) s = "0.0"; else if (precision < 53) return check( truncateToPrecision(stringToNumber(s, radix, true), precision, exact)); } // We have only one floating point width. s = String_replace(s, exponentMarkerPattern, 'e'); var dot = String_indexOf(s, '.'); var e = String_indexOf(s, 'e'); if (dot === -1 && e === -1) return parseUinteger(s, sign); if (!RegExp_test(decimal10Pattern, s)) lose(); if (!exact) return parseInexact(sign, s); var integer = String_substring(s, 0, dot === -1 ? e : dot); var exponent = ZERO; var fraction; if (e === -1) fraction = String_substring(s, dot + 1); else { if (dot === -1) fraction = ""; else fraction = String_substring(s, dot + 1, e); exponent = parseReal(String_substring(s, e + 1)); } return exp10(parseExactInteger(sign, integer + fraction), subtract(exponent, nativeToExactInteger(fraction.length))); } function parseComplex(s) { var a = String_indexOf(s, '@'); if (a !== -1) { var ret = makePolar(parseReal(String_substring(s, 0, a)), parseReal(String_substring(s, a + 1))); if (exact && isInexact(ret)) // XXX I don't think this is right. If Scheme // allows this, then by analogy, nothing requires // (numerator #e0.1) to equal 1. //ret = toExact(ret); ret = ret; // ignore #e. return ret; } if (s[s.length - 1] !== "i") return parseReal(s); if (s === "i") { if (exact === false) return inexactRectangular(INEXACT_ZERO, INEXACT_ONE); return I; } if (s === "-i") { if (exact === false) return inexactRectangular(INEXACT_ZERO, negate(INEXACT_ONE)); return MINUS_I; } var match = (radix === 10 ? decimalComplex : radixComplex).exec(s); var x, y; if (match) { x = match[1]; y = match[2]; x = (x ? parseReal(x) : (exact === false ? INEXACT_ZERO : ZERO)); y = (y === "+" ? ONE : (y === "-" ? MINUS_ONE : parseReal(y))); } else { // Could be, for example, "3i". x = (exact === false ? INEXACT_ZERO : ZERO); y = parseReal(String_substring(s, 0, s.length - 1)); } return makeRectangular(x, y); } // Common cases first. if (!radix || radix === 10) { if (RegExp_test(/^-?[0-9]{1,15}$/, s)) { if (exact === false) return nativeToInexact(_parseInt(s, 10)); return nativeToExactInteger(_parseInt(s, 10)); } } var i = 0; try { while (s[i] === "#") { switch (s[i+1]) { case 'i': case 'I': setExact(false); break; case 'e': case 'E': setExact(true ); break; case 'b': case 'B': setRadix( 2); break; case 'o': case 'O': setRadix( 8); break; case 'd': case 'D': setRadix(10); break; case 'x': case 'X': setRadix(16); break; default: return false; } i += 2; } radix = radix || 10; return parseComplex(String_substring(s, i)); } catch (e) { if (e === PARSE_ERROR) return false; if (s == _undefined) raise("&assertion", "missing argument"); throw e; } } // // End library function definitions. // api.I = I; api.ZERO = ZERO; api.ONE = ONE; api.TWO = TWO; api.MINUS_ONE = MINUS_ONE; api.INEXACT_ZERO = INEXACT_ZERO; api.INEXACT_ONE = INEXACT_ONE; api.PI = PI; api.INFINITY = INFINITY; api.MINUS_INFINITY = MINUS_INFINITY; api.NAN = NAN; api.raise = raise; api.defaultRaise = defaultRaise; api.raiseDivisionByExactZero = raiseDivisionByExactZero; api.stringToNumber = stringToNumber; api.isNumber = isNumber; api.assertReal = assertReal; api.toReal = toReal; api.assertRational = assertRational; api.toRational = toRational; api.assertInteger = assertInteger; api.toInteger = toInteger; api.assertExact = assertExact; api.makeRectangular = makeRectangular; api.makePolar = makePolar; api.truncateToPrecision = truncateToPrecision; api.retFalse = retFalse; api.retTrue = retTrue; api.retThis = retThis; api.retZero = retZero; api.retOne = retOne; api.retFirst = retFirst; return api; } /* Function: implementRnrsBase(plugins) Creates and returns the <SchemeNumber.fn> function collection. Input: *plugins* shall be a <PluginContainer> containing the public <SchemeNumber> object under the name *SchemeNumber*, as well as the output of <defineGenericFunctions> and <implementCoreLibrary>. The required plugins may be added between the call to <implementRnrsBase> and the first use of its results. About: Function list All <Scheme functions> are specified by <R6RS at http://www.r6rs.org/>. In the list below, argument names indicate applicable types as follows: obj - any value z - any Scheme number x - a real number y - a real number q - a rational number (excludes infinities and NaN) n - an integer k - an exact, non-negative integer radix - an exact integer, either 2, 8, 10, or 16 precision - an exact, positive integer Functions: Scheme functions Elements of <fn>. Refer to the argument type key under <Function list>. fn["number?"](obj) - Returns true if *obj* is a Scheme number. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_440>. fn["complex?"](obj) - Returns true if *obj* is a Scheme complex number. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_442>. fn["real?"](obj) - Returns true if *obj* is a Scheme real number. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_444>. fn["rational?"](obj) - Returns true if *obj* is a Scheme rational number. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_446>. fn["integer?"](obj) - Returns true if *obj* is a Scheme integer. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_448>. fn["real-valued?"](obj) - Returns true if *obj* is a Scheme complex number and *fn["imag-part"](obj)* is zero. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_450>. fn["rational-valued?"](obj) - Returns true if *obj* is real-valued and *fn["real-part"](obj)* is rational. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_452>. fn["integer-valued?"](obj) - Returns true if *obj* is real-valued and *fn["real-part"](obj)* is an integer. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_454>. fn["exact?"](z) - Returns true if *z* is exact. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_456>. fn["inexact?"](z) - Returns true if *z* is inexact. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_458>. fn.inexact(z) - Returns an inexact number equal to *z*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_460>. fn.exact(z) - Returns an exact number equal to *z*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_462>. fn["eqv?"](obj1, obj2) - Returns true if *obj1 === obj2* or both arguments are Scheme numbers and behave identically. Specified by <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_428>. fn["="](z, z, z...) - Returns true if all arguments are mathematically equal, though perhaps differing in exactness. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_464>. fn["<"](x, x, x...) - Returns true if arguments increase monotonically. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_466>. fn[">"](x, x, x...) - Returns true if arguments decrease monotonically. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_468>. fn["<="](x, x, x...) - Returns true if arguments are monotonically nondecreasing. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_470>. fn[">="](x, x, x...) - Returns true if arguments are monotonically nonincreasing. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_472>. fn["zero?"](z) - Returns true if *z* equals zero. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_474>. fn["positive?"](x) - Returns true if *x* is positive. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_476>. fn["negative?"](x) - Returns true if *x* is negative. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_478>. fn["odd?"](n) - Returns true if *n* is odd. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_480>. fn["even?"](n) - Returns true if *n* is even. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_482>. fn["finite?"](x) - Returns true if *x* is finite. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_484>. fn["infinite?"](x) - Returns true if *x* is plus or minus infinity. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_486>. fn["nan?"](x) - Returns true if *x* is a NaN. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_488>. fn.max(x, x...) - Returns the greatest argument. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_490>. fn.min(x, x...) - Returns the least argument. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_492>. fn["+"](z...) - Returns the sum of the arguments. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_494>. fn["*"](z...) - Returns the product of the arguments. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_496>. fn["-"](z) - Returns the negation of *z* (-*z*). Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_498>. fn["-"](z1, z2...) - Returns *z1* minus the sum of the number(s) *z2*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_500>. fn["/"](z) - Returns the reciprocal of *z* (1 / *z*). Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_502>. fn["/"](z1, z2...) - Returns *z1* divided by the product of the number(s) *z2*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_504>. fn.abs(x) - Returns the absolute value of *x*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_506>. fn["div-and-mod"](x, y) - Returns *fn.div(x, y)* and *fn.mod(x, y)*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_508>. fn.div(x, y) - Returns the greatest integer less than or equal to *x* / *y*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_510>. fn.mod(x, y) - Returns *x* - (*y* * fn.div(*x*, *y*)). Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_512>. fn["div0-and-mod0"](x, y) - Returns *fn.div0(x, y)* and *fn.mod0(x, y)*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_514>. fn.div0(x, y) - Returns the integer nearest *x* / *y*, ties go lower. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_516>. fn.mod0(x, y) - Returns *x* - (*y* * fn.div0(*x*, *y*)). Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_518>. fn.gcd(n...) - Returns the arguments' greatest common non-negative divisor. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_520>. fn.lcm(n...) - Returns the arguments' least common positive multiple. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_522>. fn.numerator(q) - Returns *q* * *fn.denominator(q)*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_524>. fn.denominator(q) - Returns the smallest positive integer which when multiplied by *q* yields an integer. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_526>. fn.floor(x) - Returns the greatest integer not greater than *x*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_528>. fn.ceiling(x) - Returns the least integer not less than *x*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_530>. fn.truncate(x) - Returns the closest integer between 0 and *x*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_532>. fn.round(x) - Returns the closest integer to *x*, ties go even. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_534>. fn.rationalize(x, y) - Returns the simplest fraction within *y* of *x*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_536>. fn.exp(z) - Returns e to the *z*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_540>. fn.log(z) - Returns the natural logarithm of *z*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_542>. fn.log(z1, z2) - Returns the base-*z2* logarithm of *z1*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_544>. fn.sin(z) - Returns the sine of *z*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_546>. fn.cos(z) - Returns the cosine of *z*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_548>. fn.tan(z) - Returns the tangent of *z*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_550>. fn.asin(z) - Returns a number whose sine is *z*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_552>. fn.acos(z) - Returns a number whose cosine is *z*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_554>. fn.atan(z) - Returns a number whose tangent is *z*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_556>. fn.atan(y, x) - Returns the angle that passes through *(x,y)*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_558>. fn.sqrt(z) - Returns the square root of *z*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_560>. fn["exact-integer-sqrt"](k) - Returns maximal exact s and non-negative r such that s*s + r = *k*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_562>. fn.expt(z1, z2) - Returns *z1* to the power *z2*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_564>. fn["make-rectangular"](x, y) - Returns the complex number *x + iy*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_566>. fn["make-polar"](r, theta) - Returns the complex number with magnitude *r* and angle *theta*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_568>. fn["real-part"](z) - Returns x such that *z* = x + iy. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_570>. fn["imag-part"](z) - Returns y such that *z* = x + iy. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_572>. fn.magnitude(z) - Returns the magnitude of *z*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_574>. fn.angle(z) - Returns *fn.atan(y,x)* where *z* = x + iy. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_576>. Function: fn["number->string"](z) Converts *z* to a string, base 10. For exact *z*, *number->string* retains full precision. Exact fractions are expressed as numerator + "/" + denominator. Examples: > fn["number->string"](fn["string->number"]("#e1.2")) // "6/5" > fn["number->string"](fn["/"]("12", "-8")) // "-3/2" Infinities are "+inf.0" and "-inf.0". NaN is "+nan.0". The result always yields a number equal to *z* (in the sense of <fn["eqv?"](obj1, obj2)>) when passed to <fn["string->number"](string)>. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_578> See Also: <fn["string->number"](string)>. Function: fn["number->string"](z, radix) Converts *z* to a string, base *radix*. *radix* must be exact 2, 8, 10, or 16. The output never contains an explicit radix prefix. The result always yields a value equal to *z* (in the sense of <fn["eqv?"](obj1, obj2)>) when converted back to a number by <fn["string->number"](string, radix)>. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_580> See Also: <fn["string->number"](string, radix)>. Function: fn["number->string"](z, radix, precision) Converts and suffixes *z* with a count of significant bits. Appends "|p" to each inexact real component of *z* where p is the smallest mantissa width not less than *precision* needed to represent the component exactly. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_582> Function: fn["string->number"](string) Parses *string* as a Scheme number. Returns *false* if unable. Examples: > "1" - exact 1. > "1." - inexact 1, same as "1.0". > "1/2" - exact one-half, same as "2/4" etc. > "0.5" - inexact 0.5. > "12e3" - inexact 12000. > "i" - the imaginary unit. > "-2+1/2i" - exact complex number. > "2.@1" - complex in polar coordinates, r=2.0, theta=1.0. > "+inf.0" - positive infinity. > "-inf.0" - negative infinity. > "+nan.0" - IEEE NaN (not-a-number). > "#e0.5" - exact one-half, forced exact by prefix #e. > "#i1/2" - 0.5, inexact by prefix #i. > "#x22" - exact 34; prefix #x hexadecimal. > "#o177" - exact 127; prefix #o octal. > "#b101" - exact 5; prefix #b binary. > "#i#b101" - inexact 5.0. > "#b#i101" - same. > "1.2345678|24" - rounded as if to single-precision (about 1.23456776). Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_584> See Also: <fn["number->string"](z)>, <R6RS section 4.2.8: Lexical syntax: Numbers at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-7.html#node_sec_4.2.8> Function: fn["string->number"](string, radix) Parses *string* as a Scheme number using *radix* as default radix. *radix* must be exact 2, 8, 10, or 16. If *string* contains a radix prefix, the prefix takes precedence over *radix*. Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_586> See Also: <fn["number->string"](z, radix)>. */ function implementRnrsBase(plugins) { //"use strict"; // Strict mode hinders error reporting. var g = plugins.get("es5globals"); var uncurry = plugins.get("uncurry"); var SchemeNumber, stringToNumber, ZERO, ONE, MINUS_ONE, INEXACT_ZERO, NAN, raise, isNumber, assertReal, toReal, toRational, toInteger, assertExact, makeRectangular, makePolar; var numberToString, isExact, isInexact, isComplex, isReal, isRational, isInteger, isZero, toExact, toInexact, negate, reciprocal, eq, ne, add, subtract, multiply, divide, realPart, imagPart, expt, exp, magnitude, angle, sqrt, log, asin, acos, atan, sin, cos, tan, SN_isFinite, SN_isInfinite, SN_isNaN, abs, isPositive, isNegative, floor, ceiling, truncate, round, compare, gt, lt, ge, le, divAndMod, div, mod, atan2, numerator, denominator, isEven, isOdd, exactIntegerSqrt, gcdNonnegative; var Array_push = uncurry(g.Array.prototype.push); SchemeNumber = plugins.get("SchemeNumber"); numberToString = plugins.get("numberToString"); isExact = plugins.get("isExact"); isInexact = plugins.get("isInexact"); isComplex = plugins.get("isComplex"); isReal = plugins.get("isReal"); isRational = plugins.get("isRational"); isInteger = plugins.get("isInteger"); isZero = plugins.get("isZero"); toExact = plugins.get("toExact"); toInexact = plugins.get("toInexact"); negate = plugins.get("negate"); reciprocal = plugins.get("reciprocal"); eq = plugins.get("eq"); ne = plugins.get("ne"); add = plugins.get("add"); subtract = plugins.get("subtract"); multiply = plugins.get("multiply"); divide = plugins.get("divide"); realPart = plugins.get("realPart"); imagPart = plugins.get("imagPart"); expt = plugins.get("expt"); exp = plugins.get("exp"); magnitude = plugins.get("magnitude"); angle = plugins.get("angle"); sqrt = plugins.get("sqrt"); log = plugins.get("log"); asin = plugins.get("asin"); acos = plugins.get("acos"); atan = plugins.get("atan"); sin = plugins.get("sin"); cos = plugins.get("cos"); tan = plugins.get("tan"); SN_isFinite = plugins.get("SN_isFinite"); SN_isInfinite = plugins.get("SN_isInfinite"); SN_isNaN = plugins.get("SN_isNaN"); abs = plugins.get("abs"); isPositive = plugins.get("isPositive"); isNegative = plugins.get("isNegative"); floor = plugins.get("floor"); ceiling = plugins.get("ceiling"); truncate = plugins.get("truncate"); round = plugins.get("round"); compare = plugins.get("compare"); gt = plugins.get("gt"); lt = plugins.get("lt"); ge = plugins.get("ge"); le = plugins.get("le");
{'commit': 'diff --git a/schemeNumber.js b/schemeNumber.js\nindex 47e1dde..118080c 100644\n--- a/schemeNumber.js\n+++ b/schemeNumber.js\n@@ -5522,12 +5522,15 @@ function implementBigInteger(plugins, BigInteger) {\n     var toBigInteger = plugins.get("Dispatch").defGeneric(\n         "to" + BigIntegerName, 1);\n \n-    var raise, numberToString, negate, reciprocal, divide, sign, exp10, nativeToInexact, inexactRectangular, ZERO, ONE, MINUS_ONE, _2_32, PI, INEXACT_ZERO;\n+    var raise, numberToString, isNegative, negate, abs, mod, reciprocal, divide, sign, exp10, nativeToInexact, inexactRectangular, ZERO, ONE, MINUS_ONE, _2_32, PI, INEXACT_ZERO;\n \n     raise                    = plugins.get("raise");\n \n     numberToString           = plugins.get("numberToString");\n+    isNegative               = plugins.get("isNegative");\n     negate                   = plugins.get("negate");\n+    abs                      = plugins.get("abs");\n+    mod                      = plugins.get("mod");\n     reciprocal               = plugins.get("reciprocal");\n     divide                   = plugins.get("divide");\n     sign                     = plugins.get("sign");\n@@ -5715,6 +5718,10 @@ function implementBigInteger(plugins, BigInteger) {\n         }\n     }\n \n+    //\n+    // BigInteger support for (rnrs arithmetic bitwise), mostly untested XXX.\n+    //\n+\n     function makeBitOp(op) {\n         function BigInteger_bitwiseOp(b) {\n             var a = this;\n@@ -5747,23 +5754,44 @@ function implementBigInteger(plugins, BigInteger) {\n     var BigInteger_bitwiseIor = makeBitOp(function(x, y) { return x | y; });\n     var BigInteger_bitwiseXor = makeBitOp(function(x, y) { return x ^ y; });\n \n+    var bitCountArray, ffsArray;\n+\n     function addOne(x) { return x + 1; }\n-    var BIT_COUNT = [0];\n-    while (BIT_COUNT.length < (1 << 8))\n-        BIT_COUNT = Array_concat(BIT_COUNT, Array_map(BIT_COUNT, addOne));\n+\n+    function getBitCountArray() {\n+        if (!bitCountArray) {\n+            bitCountArray = [0];\n+            while (bitCountArray.length < (1 << 8))\n+                bitCountArray = Array_concat(bitCountArray,\n+                                             Array_map(bitCountArray, addOne));\n+        }\n+        return bitCountArray;\n+    }\n+\n+    function getFfsArray() {\n+        if (!ffsArray) {\n+            ffsArray = [0];\n+            while (ffsArray.length < (1 << 8)) {\n+                ffsArray = ffsArray.concat(ffsArray);\n+                ffsArray[0]++;\n+            }\n+        }\n+        return ffsArray;\n+    }\n \n     function BigInteger_bitCount() {\n         //assert(!isNegative(this));\n         var a = this;\n-        var ret = 0, dm, t;\n+        var ret = 0, dm, t, bc;\n         while (!a.isZero()) {\n             dm = a.divRem(_2_32);\n             a = dm[0];\n             t = +dm[1];\n-            ret += BIT_COUNT[(t >>  0) & 0xff];\n-            ret += BIT_COUNT[(t >>  8) & 0xff];\n-            ret += BIT_COUNT[(t >> 16) & 0xff];\n-            ret += BIT_COUNT[(t >> 24) & 0xff];\n+            bc = getBitCountArray();\n+            ret += bc[(t >>  0) & 0xff];\n+            ret += bc[(t >>  8) & 0xff];\n+            ret += bc[(t >> 16) & 0xff];\n+            ret += bc[(t >> 24) & 0xff];\n         }\n         return nativeToExactInteger(ret);\n     }\n@@ -5796,12 +5824,6 @@ function implementBigInteger(plugins, BigInteger) {\n         }\n     }\n \n-    var FFS = [1, 0];\n-    while (FFS.length < (1 << 8)) {\n-        FFS = FFS.concat(FFS);\n-        FFS[0]++;\n-    }\n-\n     function BigInteger_firstBitSet() {\n         var a = this, dm, m, ret;\n         if (a.isZero())\n@@ -5818,11 +5840,11 @@ function implementBigInteger(plugins, BigInteger) {\n             ret += 8;\n             m >>= 8;\n         }\n-        return nativeToExactInteger(ret + FFS[m & 0xff]);\n+        return nativeToExactInteger(ret + getFfsArray()[m & 0xff]);\n     }\n \n     function BigInteger_isBitSet(i) {\n-        //assert(!isNegative(n));\n+        //assert(!isNegative(this));\n         var p2i = BigInteger.pow(2, +i);\n         return this.remainder(p2i.add(p2i)).compare(p2i) >= 0;\n     }\n@@ -5833,10 +5855,73 @@ function implementBigInteger(plugins, BigInteger) {\n         switch (setIt - isSet) {\n         case 0: return this;\n         case 1: return this.add(p2i);\n-        case -1: default: return this.subtract(p2i);\n+        case -1: return this.subtract(p2i);\n         }\n     }\n \n+    function BigInteger_bitField(lo, hi) {\n+        //assert(!isNegative(this));\n+        //assert(le(lo, hi));\n+        lo = +lo;\n+        var p2width = BigInteger.pow(2, hi - lo);\n+        var p2lo = BigInteger.pow(2, lo);\n+        return this.quotient(p2lo).remainder(p2width);\n+    }\n+\n+    function BigInteger_copyBitField(from, lo, hi) {\n+        //assert(!isNegative(this));\n+        //assert(!isNegative(from));\n+        //assert(le(lo, hi));\n+        lo = +lo;\n+        var p2width = BigInteger.pow(2, hi - lo);\n+        var p2lo = BigInteger.pow(2, lo);\n+        var old = this.quotient(p2lo).remainder(p2width);\n+        return this.add(p2lo.multiply(from.subtract(old).quotient(p2width)));\n+    }\n+\n+    function BigInteger_bitShift(count) {\n+        var p2 = BigInteger.pow(2, +abs(count));\n+        return (isNegative(count) ? this.quotient(p2) : this.multiply(p2));\n+    }\n+\n+    function BigInteger_rotateBitField(lo, hi, count) {\n+        //assert(!isNegative(this));\n+        //assert(le(lo, hi));\n+        lo = +lo;\n+        var width = hi - lo;\n+        if (width < 2)\n+            return this;\n+        count = +mod(count, nativeToExactInteger(width));\n+        if (count === 0)\n+            return this;\n+        var p2width = BigInteger.pow(2, width);\n+        var p2lo = BigInteger.pow(2, lo);\n+        var p2count = BigInteger.pow(2, count);\n+        var old = this.quotient(p2lo).remainder(p2width);\n+        var tmp = old.multiply(p2count);\n+        tmp = tmp.add(tmp.quotient(p2width)).remainder(p2width);\n+        return this.add(p2lo.multiply(tmp.subtract(old)));\n+    }\n+\n+    function BigInteger_reverseBitField(lo, hi) {\n+        //assert(!isNegative(this));\n+        //assert(le(lo, hi));\n+        var i;\n+        lo = +lo;\n+        var p2width = BigInteger.pow(2, hi - lo);\n+        var p2lo = BigInteger.pow(2, +lo);\n+        var bits = this.quotient(p2lo).remainder(p2width);\n+        var string = bits.toString(2);\n+        var last = string.length - 1;\n+        if (last < 1)\n+            return this;\n+        var revString = "";\n+        for (i = 0; i < string.length; i++)\n+            revString += string[last - i];\n+        var reversed = BigInteger.parse(revString, 2);\n+        return this.add(reversed.subtract(bits).multiply(p2lo));\n+    }\n+\n     function install() {\n         "use strict";\n         var disp                     = plugins.get("Dispatch");\n@@ -5904,6 +5989,11 @@ function implementBigInteger(plugins, BigInteger) {\n         def1("firstBitSet", BigInteger_firstBitSet);\n         def1("isBitSet",   BigInteger_isBitSet);\n         def1("copyBit",    BigInteger_copyBit);\n+        def1("bitField",   BigInteger_bitField);\n+        def2("copyBitField", BigInteger_copyBitField);\n+        def1("bitShift",   BigInteger_bitShift);\n+        def1("rotateBitField", BigInteger_rotateBitField);\n+        def1("reverseBitField", BigInteger_reverseBitField);\n     }\n \n     api.parseExactInteger        = parseExactInteger;\n', 'commit_subject': 'Bitwise operations for BigInteger.', 'repo_name': 'jtobey/javascript-bignum', 'committer': {'name': 'John Tobey', 'email': 'bfded4df13c9d2fb2e25e193d3acd3674a51cb9a@gmail.com', 'time_sec': '1332949153', 'tz_offset': '-240', 'date': {'seconds': '1332949153'}}, 'commit_tree': '587e6a0727e51166ff647a0ab78e2d1bd73438f2', 'commit_message': 'Bitwise operations for BigInteger.\n', 'language_name': 'Perl', 'license': 'mit', 'hunks': '@@ -5522,12 +5522,15 @@ function implementBigInteger(plugins, BigInteger) {\n     var toBigInteger = plugins.get("Dispatch").defGeneric(\n         "to" + BigIntegerName, 1);\n \n-    var raise, numberToString, negate, reciprocal, divide, sign, exp10, nativeToInexact, inexactRectangular, ZERO, ONE, MINUS_ONE, _2_32, PI, INEXACT_ZERO;\n+    var raise, numberToString, isNegative, negate, abs, mod, reciprocal, divide, sign, exp10, nativeToInexact, inexactRectangular, ZERO, ONE, MINUS_ONE, _2_32, PI, INEXACT_ZERO;\n \n     raise                    = plugins.get("raise");\n \n     numberToString           = plugins.get("numberToString");\n+    isNegative               = plugins.get("isNegative");\n     negate                   = plugins.get("negate");\n+    abs                      = plugins.get("abs");\n+    mod                      = plugins.get("mod");\n     reciprocal               = plugins.get("reciprocal");\n     divide                   = plugins.get("divide");\n     sign                     = plugins.get("sign");\n@@ -5715,6 +5718,10 @@ function implementBigInteger(plugins, BigInteger) {\n         }\n     }\n \n+    //\n+    // BigInteger support for (rnrs arithmetic bitwise), mostly untested XXX.\n+    //\n+\n     function makeBitOp(op) {\n         function BigInteger_bitwiseOp(b) {\n             var a = this;\n@@ -5747,23 +5754,44 @@ function implementBigInteger(plugins, BigInteger) {\n     var BigInteger_bitwiseIor = makeBitOp(function(x, y) { return x | y; });\n     var BigInteger_bitwiseXor = makeBitOp(function(x, y) { return x ^ y; });\n \n+    var bitCountArray, ffsArray;\n+\n     function addOne(x) { return x + 1; }\n-    var BIT_COUNT = [0];\n-    while (BIT_COUNT.length < (1 << 8))\n-        BIT_COUNT = Array_concat(BIT_COUNT, Array_map(BIT_COUNT, addOne));\n+\n+    function getBitCountArray() {\n+        if (!bitCountArray) {\n+            bitCountArray = [0];\n+            while (bitCountArray.length < (1 << 8))\n+                bitCountArray = Array_concat(bitCountArray,\n+                                             Array_map(bitCountArray, addOne));\n+        }\n+        return bitCountArray;\n+    }\n+\n+    function getFfsArray() {\n+        if (!ffsArray) {\n+            ffsArray = [0];\n+            while (ffsArray.length < (1 << 8)) {\n+                ffsArray = ffsArray.concat(ffsArray);\n+                ffsArray[0]++;\n+            }\n+        }\n+        return ffsArray;\n+    }\n \n     function BigInteger_bitCount() {\n         //assert(!isNegative(this));\n         var a = this;\n-        var ret = 0, dm, t;\n+        var ret = 0, dm, t, bc;\n         while (!a.isZero()) {\n             dm = a.divRem(_2_32);\n             a = dm[0];\n             t = +dm[1];\n-            ret += BIT_COUNT[(t >>  0) & 0xff];\n-            ret += BIT_COUNT[(t >>  8) & 0xff];\n-            ret += BIT_COUNT[(t >> 16) & 0xff];\n-            ret += BIT_COUNT[(t >> 24) & 0xff];\n+            bc = getBitCountArray();\n+            ret += bc[(t >>  0) & 0xff];\n+            ret += bc[(t >>  8) & 0xff];\n+            ret += bc[(t >> 16) & 0xff];\n+            ret += bc[(t >> 24) & 0xff];\n         }\n         return nativeToExactInteger(ret);\n     }\n@@ -5796,12 +5824,6 @@ function implementBigInteger(plugins, BigInteger) {\n         }\n     }\n \n-    var FFS = [1, 0];\n-    while (FFS.length < (1 << 8)) {\n-        FFS = FFS.concat(FFS);\n-        FFS[0]++;\n-    }\n-\n     function BigInteger_firstBitSet() {\n         var a = this, dm, m, ret;\n         if (a.isZero())\n@@ -5818,11 +5840,11 @@ function implementBigInteger(plugins, BigInteger) {\n             ret += 8;\n             m >>= 8;\n         }\n-        return nativeToExactInteger(ret + FFS[m & 0xff]);\n+        return nativeToExactInteger(ret + getFfsArray()[m & 0xff]);\n     }\n \n     function BigInteger_isBitSet(i) {\n-        //assert(!isNegative(n));\n+        //assert(!isNegative(this));\n         var p2i = BigInteger.pow(2, +i);\n         return this.remainder(p2i.add(p2i)).compare(p2i) >= 0;\n     }\n@@ -5833,10 +5855,73 @@ function implementBigInteger(plugins, BigInteger) {\n         switch (setIt - isSet) {\n         case 0: return this;\n         case 1: return this.add(p2i);\n-        case -1: default: return this.subtract(p2i);\n+        case -1: return this.subtract(p2i);\n         }\n     }\n \n+    function BigInteger_bitField(lo, hi) {\n+        //assert(!isNegative(this));\n+        //assert(le(lo, hi));\n+        lo = +lo;\n+        var p2width = BigInteger.pow(2, hi - lo);\n+        var p2lo = BigInteger.pow(2, lo);\n+        return this.quotient(p2lo).remainder(p2width);\n+    }\n+\n+    function BigInteger_copyBitField(from, lo, hi) {\n+        //assert(!isNegative(this));\n+        //assert(!isNegative(from));\n+        //assert(le(lo, hi));\n+        lo = +lo;\n+        var p2width = BigInteger.pow(2, hi - lo);\n+        var p2lo = BigInteger.pow(2, lo);\n+        var old = this.quotient(p2lo).remainder(p2width);\n+        return this.add(p2lo.multiply(from.subtract(old).quotient(p2width)));\n+    }\n+\n+    function BigInteger_bitShift(count) {\n+        var p2 = BigInteger.pow(2, +abs(count));\n+        return (isNegative(count) ? this.quotient(p2) : this.multiply(p2));\n+    }\n+\n+    function BigInteger_rotateBitField(lo, hi, count) {\n+        //assert(!isNegative(this));\n+        //assert(le(lo, hi));\n+        lo = +lo;\n+        var width = hi - lo;\n+        if (width < 2)\n+            return this;\n+        count = +mod(count, nativeToExactInteger(width));\n+        if (count === 0)\n+            return this;\n+        var p2width = BigInteger.pow(2, width);\n+        var p2lo = BigInteger.pow(2, lo);\n+        var p2count = BigInteger.pow(2, count);\n+        var old = this.quotient(p2lo).remainder(p2width);\n+        var tmp = old.multiply(p2count);\n+        tmp = tmp.add(tmp.quotient(p2width)).remainder(p2width);\n+        return this.add(p2lo.multiply(tmp.subtract(old)));\n+    }\n+\n+    function BigInteger_reverseBitField(lo, hi) {\n+        //assert(!isNegative(this));\n+        //assert(le(lo, hi));\n+        var i;\n+        lo = +lo;\n+        var p2width = BigInteger.pow(2, hi - lo);\n+        var p2lo = BigInteger.pow(2, +lo);\n+        var bits = this.quotient(p2lo).remainder(p2width);\n+        var string = bits.toString(2);\n+        var last = string.length - 1;\n+        if (last < 1)\n+            return this;\n+        var revString = "";\n+        for (i = 0; i < string.length; i++)\n+            revString += string[last - i];\n+        var reversed = BigInteger.parse(revString, 2);\n+        return this.add(reversed.subtract(bits).multiply(p2lo));\n+    }\n+\n     function install() {\n         "use strict";\n         var disp                     = plugins.get("Dispatch");\n@@ -5904,6 +5989,11 @@ function implementBigInteger(plugins, BigInteger) {\n         def1("firstBitSet", BigInteger_firstBitSet);\n         def1("isBitSet",   BigInteger_isBitSet);\n         def1("copyBit",    BigInteger_copyBit);\n+        def1("bitField",   BigInteger_bitField);\n+        def2("copyBitField", BigInteger_copyBitField);\n+        def1("bitShift",   BigInteger_bitShift);\n+        def1("rotateBitField", BigInteger_rotateBitField);\n+        def1("reverseBitField", BigInteger_reverseBitField);\n     }\n \n     api.parseExactInteger        = parseExactInteger;\n', 'addition_count': 108, 'deletion_count': 18, 'src_file': 'a/schemeNumber.js', 'tgt_file': 'b/schemeNumber.js', 'file_extension': '.js', 'before_file': '// Scheme numerical tower in JavaScript.\n// Copyright (c) 2011,2012 by John Tobey <jtobey@john-edwin-tobey.org>\n\n/*\n    File: schemeNumber.js\n\n    Exports:\n\n        <SchemeNumber>\n\n    Depends:\n\n        <biginteger.js> for <BigInteger>\n */\n\n/*\n    Class: SchemeNumber\n    A number object as <defined by the Scheme language at\n    http://www.r6rs.org/>.\n\n    Scheme supports *exact* arithmetic and mixing exact with standard\n    (*inexact*) numbers.  Several basic operations, including\n    addition, subtraction, multiplication, and division, when given\n    only exact arguments, must return an exact, numerically correct\n    result.\n\n    These operations are allowed to fail due to running out of memory,\n    but they are not allowed to return approximations the way\n    ECMAScript operators may, unless given one or more inexact\n    arguments.\n\n    For example, adding exact *1/100* to exact *0* one hundred times\n    produces exactly *1*, not 1.0000000000000007 as in JavaScript.\n    Raising exact *2* to the power of exact *1024* returns a 308-digit\n    integer with complete precision, not *Infinity* as in ECMAScript.\n\n    This implementation provides all functions listed in the <R6RS\n    Scheme specification at http://www.r6rs.org/>, Section 11.7, along\n    with <eqv?> from Section 11.5.  (<eqv?> uses JavaScript\'s *===* to\n    compare non-numbers.)\n\n    Exact numbers support the standard ECMA Number formatting methods\n    (toFixed, toExponential, and toPrecision) without a fixed upper\n    limit to precision.\n\n    The schemeNumber.js file exports an object <SchemeNumber>.  It\n    contains a property <fn>, which in turn contains the functions\n    implementing the numeric types.\n\n    The <SchemeNumber> object is in fact a function that converts its\n    argument to a Scheme number: similar to a constructor, but it may\n    not always return an object, let alone a unique object.\n\n    Parameters:\n\n        obj - Object to be converted to a Scheme number.\n\n    *obj* may have any of the following\n    types:\n\n        Scheme number - returned unchanged.\n        String        - converted as if by *string->number*.\n        Native ECMAScript number - treated as an inexact real.\n\n    Returns:\n\n        A Scheme number.\n\n    Exceptions:\n\n        If *obj* can not be parsed, <SchemeNumber> will <raise> an\n        exception with condition type *&assertion*.\n\n    See Also:\n\n        <fn>, <raise>, <R6RS Chapter 3: Numbers at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-6.html#node_chap_3>\n*/\nvar SchemeNumber = (function() {\n\n//\n// Multiple dispatch support.\n//\n\nvar DispatchJs = (function() {\n"use strict";\n/*\nMultiple dispatch for JavaScript functions of fixed arity.  Example:\n\n    // B and C inherit from A.  D inherits from C.\n    var A = disp.defClass("A", {ctor: function(x) { this.x = x }});\n    var B = disp.defClass("B", {base: "A"});\n    var C = disp.defClass("C", {base: "A"});\n    // Classes may be defined after their superclass methods.\n    //var D = disp.defClass("D", {base: "C"});\n\n    // Or you can declare existing classes:\n    //var disp = DispatchJs;\n    //function A(){} A.prototype = {};\n    //disp.defClass("A", {ctor: A});\n    //function B(){} B.prototype = new A();\n    //disp.defClass("B", {ctor: B, base "A"});\n    //function C(){} C.prototype = new A();\n    //disp.defClass("C", {ctor: C, base "A"});\n    //function D(){} D.prototype = new C();\n    //disp.defClass("D", {ctor: D, base "C"});\n\n    // This creates a function of 2 arguments:\n    var frob = disp.defGeneric("frob", 2);\n\n    // Define methods.  Methods receive frob\'s first argument as "this" and\n    // the rest as method arguments.\n    frob.def("A", "A", function(a1) { return "A A" });\n    frob.def("A", "B", function(a1) { return "A B" });\n    frob.def("B", "A", function(a1) { return "B A" });\n    frob.def("B", "B", function(a1) { return "B B" });\n    frob.def("A", "C", function(a1) { return "A C" });\n    var D = disp.defClass("D", function(x) { this.x = x }, "C");\n    frob.def("D", "D", function(a1) { return "D D" });\n\n    // Create some arguments:\n    var a = new A();\n    var b = new B();\n    var c = new C();\n    var d = new D();\n\n    // Call the function:\n    frob(a,a);  // "A A"\n    frob(a,b);  // "A B"\n    frob(a,c);  // "A C"\n    frob(a,d);  // "A C"\n    frob(b,a);  // "B A"\n    frob(b,b);  // "B B"\n    frob(b,c);  // "B A" or "A C"\n    frob(b,d);  // "B A" or "A C"\n    frob(c,a);  // "A A"\n    frob(c,b);  // "A B"\n    frob(c,c);  // "A C"\n    frob(c,d);  // "A C"\n    frob(d,a);  // "A A"\n    frob(d,b);  // "A B"\n    frob(d,c);  // "A C"\n    frob(d,d);  // "D D"\n\nAmbiguous calls such as frob(b,c) and frob(b,d) above use whichever of\nthe best candidates was defined first: the method for types B,A or the\none for A,C.\n*/\n\nfunction short_fn(f) {\n    return String(f).replace(/(?:.|\\n)*(function .*?\\(.*?\\))(?:.|\\n)*/, "$1");\n}\n\nvar Formals = [];\n\nfunction makeContext(opts) {\n\n    var g = opts.globals;\n    var _Function = (g ? g.Function : Function);\n    var uncurry = _Function.prototype.bind.bind(_Function.prototype.call);\n    var _Object   = (g ? g.Object   : Object);\n    var _String   = (g ? g.String   : String);\n    var _Array    = (g ? g.Array    : Array);\n    var _Error    = (g ? g.Error    : Error);\n    var _apply   = uncurry(_Function.prototype.apply);\n    var _slice   = uncurry(_Array.prototype.slice);\n    var _join    = uncurry(_Array.prototype.join);\n    var _push    = uncurry(_Array.prototype.push);\n    var _unshift = uncurry(_Array.prototype.unshift);\n    var _forEach = uncurry(_Array.prototype.forEach);\n    var _concat  = uncurry(_Array.prototype.concat);\n    var _replace = uncurry(_String.prototype.replace);\n    var _split   = uncurry(_String.prototype.split);\n    var _create  = _Object.create;\n    var _hasOwnProperty = uncurry(_Object.prototype.hasOwnProperty);\n    var String_indexOf = uncurry(_String.prototype.indexOf);\n    var Array_indexOf  = uncurry(_Array.prototype.indexOf);\n\n    var prefix = opts.methodNamePrefix || "_jsmd";\n    var ePrefix = _replace(prefix, /([\\"\\\\])/g, "\\\\$1");\n    var sep = opts.methodNameSeparator || " ";\n    var classes = _create(null);\n\n    function classToName(cl) {\n        if (cl != null) {\n            var name = cl[prefix];\n            if (typeof name === "string")\n                if (classes[name] && classes[name].ctor === cl)\n                    return name;\n            else\n                for (name in classes)\n                    if (classes[name] && classes[name].ctor === cl)\n                        return name;\n        }\n    }\n    function assertClassToName(cl) {\n        if ("string" === typeof cl)\n            return cl;\n        var ret = classToName(cl);\n        if (ret)\n            return ret;\n        throw _Error("Class not defined: " + cl);\n    }\n\n    function pureVirtual() {\n        var msg = "Abstract method not overridden for ";\n        try {\n            msg += this;\n        }\n        catch (e) {\n            try {\n                msg += _Object.prototype.toString.call(this);\n            }\n            catch (e) {\n                msg += "object";\n            }\n        }\n        throw new _Error(msg);\n    }\n\n    var ret = {\n        getConstructor: function(name) {\n            return classes[name] && classes[name].ctor;\n        },\n        defClass: function(name, opts) {\n            var ctor, base;\n            var bctor, proto, key, sub, sepBase, cname, c;\n            var ometh, meth, func, array, doit, i, indices;\n\n            opts.debug && console.log("defClass: ", name);\n            if (opts) {\n                ctor = opts.ctor;\n                if (opts.base)\n                    base = assertClassToName(opts.base);\n            }\n            if (typeof base === "undefined" && ctor && ctor.prototype != null) {\n                base = classToName(ctor.prototype.constructor);\n            }\n            //opts.debug && console.log("base:", base);\n            if (typeof base !== "undefined") {\n                bctor = classes[base].ctor;\n            }\n            ctor = ctor || function(){}\n            if (typeof name !== "string") {\n                throw _Error("Usage: defClass(NAME, [OPTS])");\n            }\n            if (classes[name]) {\n                if (classes[name].ctor !== ctor || classes[name].base !== base)\n                {\n                    throw _Error("Can\'t redefine class " + name);\n                }\n                return ctor;\n            }\n            if (String_indexOf(name, sep) != -1) {\n                throw _Error((sep == " " ? "Space" : "Separator") +\n                             " in class name: " + name);\n            }\n            if (typeof (ctor[prefix]) !== "undefined") {\n                if (ctor[prefix] !== name)\n                    throw _Error("Cannot define constructor as " + name +\n                                 ", it was previously defined as " +\n                                 ctor[prefix]);\n            }\n            else {\n                ctor[prefix] = name;\n            }\n            //opts.debug && console.log("checking prototype constructor");\n            if (ctor.prototype) {\n                if (_hasOwnProperty(ctor.prototype, "constructor")) {\n                    if (ctor.prototype.constructor !== ctor)\n                        throw _Error("ctor.prototype.constructor is not ctor");\n                }\n                else {\n                    ctor.prototype.constructor = ctor;\n                }\n            }\n            //opts.debug && console.log("ok")\n            if (!ctor.prototype ||\n                (bctor && !(ctor.prototype instanceof bctor)))\n            {\n                proto = (bctor ? new bctor() : _create(null));\n                //opts.debug && console.log("proto.constructor[prefix]", proto.constructor[prefix]);\n                if (ctor.prototype) {\n                    // XXX Used for BigInteger; too hacky?\n                    for (key in ctor.prototype) {\n                        proto[key] = ctor.prototype[key];\n                    }\n                }\n                proto.constructor = ctor;\n                ctor.prototype = proto;\n            }\n            classes[name] = {\n                ctor:    ctor,\n                base:    base,\n                sub:     [],\n                ename:   _replace(sep + name, /([\\"\\\\])/g, "\\\\$1")\n            };\n            //opts.debug && console.log("defClass:", name, "base:", base);\n            if (typeof base !== "undefined") {\n                sub = classes[base].sub;\n                if (Array_indexOf(sub, name) === -1)\n                    _push(sub, name);\n                sepBase = sep + base;\n                for (cname in classes) {\n                    proto = classes[cname].ctor.prototype;\n                    for (ometh in proto) {\n                        if (!_hasOwnProperty(proto, ometh))\n                            continue;\n                        if (!String_indexOf(ometh, sepBase))\n                            continue;\n                        array = _split(ometh, sep);\n                        if (array[0] !== prefix)\n                            continue;\n                        func = proto[ometh];\n                        indices = [];\n                        for (i = Array_indexOf(array, base, 2); i !== -1;\n                             i = Array_indexOf(array, base, i + 1)) {\n                            _push(indices, i);\n                        }\n                        doit = function(i) {\n                            if (i === indices.length) {\n                                meth = _join(array, sep);\n                                if (meth !== ometh) {\n                                    opts.debug && console.log(cname + \'["\'+meth+\'"] propagated -> \' + short_fn(func));\n                                    proto[meth] = func;\n                                }\n                                return;\n                            }\n                            array[indices[i]] = base;\n                            doit(i + 1);\n                            array[indices[i]] = name;\n                            doit(i + 1);\n                        }\n                        doit(0);\n                    }\n                }\n            }\n            return ctor;\n        },\n\n        defGeneric: function (fnName, ndisp, nargs) {\n            if (String_indexOf(fnName, sep) != -1)\n                throw _Error((sep == " " ? "Space" : "Separator") +\n                             " in function name: " + fnName);\n            nargs = nargs || ndisp;\n            if (fnName == ""\n                || ndisp < 1 || ndisp != (ndisp | 0)\n                || nargs < 1 || nargs != (nargs | 0))\n                throw Error("Usage: defGeneric(NAME, NDISP [, NARGS])");\n\n            var eName = _replace(sep + fnName, /([\\"\\\\])/g, "\\\\$1");\n            var eTopMethod = ePrefix + eName;\n\n            for (var i = Formals.length; i < nargs; i++)\n                Formals[i] = "a" + i;\n            var array = _slice(Formals, 0, nargs);\n            // e.g., function(a0,a1,a2,a3){return a3["_jsmd frob"](a0,a1,a2)}\n            _push(array,\n                  "return " + Formals[ndisp-1] + \'["\' + eTopMethod + \'"](\' +\n                  _join(_concat(_slice(array, 0, ndisp-1),\n                                _slice(array, ndisp, nargs)), ",") + \')\')\n            var ret = _apply(_Function, null, array);\n\n            var func_cache = _create(null);\n            function get_func(i, etypes) {\n                var suffix = _join(_slice(etypes, i), "");\n                if (!func_cache[suffix]) {\n                    var method = ePrefix + eName + suffix;\n                    var array = _concat(_slice(Formals, 0,i),\n                                        _slice(Formals, i+1, nargs));\n\n                    _push(array, "return " + Formals[i-1] +\n                          \'["\' + method + \'"](\' +\n                          _join(_concat(_slice(Formals, 0, i-1), "this",\n                                        _slice(Formals, i+1, nargs)), ",") +\n                          \')\');\n\n                    func_cache[suffix] = _apply(_Function, null, array);\n                }\n                return func_cache[suffix];\n            }\n\n            // For error message.\n            function usageArgs() {\n                switch (ndisp) {\n                case 1: return "TYPE";\n                case 2: return "TYPE1, TYPE2";\n                case 3: return "TYPE1, TYPE2, TYPE3";\n                default: return "TYPE1, ..., TYPE" + ndisp;\n                }\n            }\n\n            // def(TYPE1, ..., TYPEn, FUNCTION)\n            // Defines FUNCTION as this method\'s specialization for the\n            // given types.  Each TYPEi must have been passed as the\n            // NAME argument in a successful call to defClass.\n            function def() {\n                var fn = arguments[ndisp] || pureVirtual;\n                if (typeof fn !== "function") {\n                    throw _Error("Not a function.  Usage: " + fnName +\n                                 ".def(" + usageArgs() + ", FUNCTION)");\n                }\n                var types = _slice(arguments, 0, ndisp);\n                //opts.debug && console.log("def", fnName, types, short_fn(fn));\n\n                for (i = 0; i < ndisp; i++) {\n                    // Throw error if not registered.\n                    // XXX Could add def() arguments to a list to be\n                    // defined during defClass.\n                    types[i] = assertClassToName(types[i]);\n                }\n                //opts.debug && console.log("def");\n                do_def(types, fn, _create(null));\n            }\n\n            function do_def(types, fn, inherited) {\n                var cs = new _Array(ndisp);\n                var eTypes = new _Array(ndisp);\n                var i, suffix, oldm, newm;\n\n                for (i = 0; i < ndisp; i++) {\n                    cs[i] = classes[types[i]];\n                    //opts.debug && console.log("cs[" + i + "]=classes[", types[i], "]");\n                    eTypes[i] = cs[i].ename;\n                }\n                opts.debug && console.log("do_def", fnName, eTypes);\n\n                oldm = new Array(ndisp);\n                for (i = ndisp-1, suffix = ""; ; i--) {\n                    oldm[i] = cs[i].ctor.prototype[\n                        prefix + sep + fnName + suffix];\n                    //opts.debug && console.log("oldm[" + i + "]" + oldm[i]);\n                    if (i === 0)\n                        break;\n                    suffix = eTypes[i] + suffix;\n                }\n\n                newm = new _Array(ndisp);\n                newm[0] = fn;\n                for (i=1; i<ndisp; i++)\n                    newm[i] = get_func(i, eTypes);\n\n                function doit(i, method) {\n                    var key;\n                    var proto = cs[i].ctor.prototype;\n\n                    if (proto[method] && proto[method] !== oldm[i]) {\n                        opts.debug && console.log("Skipping " + i + " " + types[i] + \'["\' + method + \'"] \' + short_fn(proto[method]) + "!=" + short_fn(oldm[i]));\n                        return;  // already more specialized in an argument.\n                    }\n                    //console.log("doit("+i+","+method+")  "+cs[i].ename);\n                    if (proto === Object.prototype) // sanity check.\n                        throw Error("BUG: code would modify Object.prototype.");\n\n                    if (proto[method] !== newm[i]) {\n                        key = types[i] + sep + method;\n                        if ((key in inherited) && newm[i] === inherited[key]) {\n                            opts.debug && console.log(eTypes[i] + \'["\'+method+\'"] \' + short_fn(proto[method]) + " -> DELETED");\n                            delete(proto[method]);\n                        }\n                        else {\n                            opts.debug && console.log(eTypes[i] + \'["\'+method+\'"] \' + short_fn(proto[method]) + " -> " + short_fn(newm[i]));\n                            if (!_hasOwnProperty(proto, method)) {\n                                inherited[key] = proto[method];\n                            }\n                            proto[method] = newm[i];\n                        }\n                    }\n                    if (i === 0)\n                        return;\n                    function doit2(k) {\n                        doit(i - 1, method + sep + k);\n                        _forEach(classes[k].sub, doit2);\n                    }\n                    doit2(types[i]);\n                }\n\n                doit(ndisp-1, prefix + sep + fnName);\n            }\n            ret.def = def;\n            return ret;\n        }\n        // lookup: TO DO\n    };\n    if (opts.debug)\n        ret.classes = classes;\n    return ret;\n}\nvar ret = makeContext(Object.create(null));\nret.makeContext = makeContext;\nreturn ret;\n})();\n\n//if (typeof exports !== "undefined") {\n//    exports.DispatchJs = DispatchJs;\n//    exports.makeContext = DispatchJs.makeContext;\n//    exports.defClass = DispatchJs.defClass;\n//    exports.defGeneric = DispatchJs.defGeneric;\n//}\n\n\n/*\n    Constructor: PluginContainer(plugins)\n    A PluginContainer is just a set of properties, referred to as\n    "plugins", with an interface to change them and subscribe to\n    notification of such changes.\n\n    If *plugins* is passed, it is stored as if via <extend> as the\n    initial set of plugins.\n*/\nfunction PluginContainer(init) {\n    "use strict";\n\n    // XXX use of globals via Array and Function methods, Object,\n    // Error, and undefined: should virtualize.\n\n    if (!(this instanceof PluginContainer))\n        throw Error("Usage: new PluginContainer()");\n\n    var t = this, listeners = [], plugins = Object.create(null);\n\n    function mergeChanges(from, to, changed) {\n        var ret = false;\n        for (var i in from) {\n            if (to[i] !== undefined && to[i] !== from[i])\n                throw Error("Conflicting changes to " + i);\n            if (changed)\n                changed[i] = from[i];\n            to[i] = from[i];\n            ret = true;\n        }\n        return ret;\n    }\n\n    /*\n    Property: onChange\n    Event used to publish changes to plugins.\n\n    > plugins.onChange.subscribe(listener);\n\n    After <extend> changes one or more plugin values, it calls\n    *listener* with two arguments: the <PluginContainer> and an object\n    whose properties are the changed plugins.\n\n    No call results from passing <extend> an empty object or one whose\n    values all equal the current corresponding plugins.\n\n    > plugins.onChange.unsubscribe(listener);\n\n    Reverses the effect of an earlier *subscribe* call.\n    */\n    var onChange = {\n\n        fire: function(changes) {\n            function notify(listener) {\n                listener.call(listener, t, changes);\n            }\n            listeners.forEach(notify);\n        },\n\n        subscribe: function(listener) {\n            listeners.push(listener);\n        },\n        unsubscribe: function(listener) {\n            function isNotIt(l) { return l !== listener; }\n            listeners = listeners.filter(isNotIt);\n        }\n    };\n    t.onChange = onChange;\n\n    /*\n    Method: extend(newPlugins)\n    Adds or replaces plugins in the container.\n\n    *newPlugins* must be an object.  All of its properties\n    (technically, its own, enumerable properties) are stored as new or\n    replacement plugins.  If this results in any actual changes, all\n    of the container\'s <onChange> listeners are notified.\n\n    Method: extend(name1, plugin1, name2, plugin2, ...)\n    Like extend({ *name1* : *plugin1*, *name2* : *plugin2*, ... })\n    */\n    t.extend = function() {\n        var changes = Object.create(null);\n        var newPlugins = arguments[0], i;\n\n        if (typeof newPlugins !== "object") {\n            if (arguments.length & 1)\n                throw Error("extend: Wrong argument types");\n            newPlugins = Object.create(null);\n            for (i = 0; i < arguments.length; i += 2) {\n                if (arguments[i] in newPlugins)\n                    throw Error("extend: " + arguments[i] +\n                                " given more than once");\n                newPlugins[arguments[i]] = arguments[i+1];\n            }\n        }\n        if (mergeChanges(newPlugins, plugins, changes))\n            onChange.fire(changes);\n    };\n\n    /*\n    Method: get(pluginName)\n    Returns the plugin named *pluginName*, or *undefined* if none\n    exists by that name.\n    */\n    t.get = function(pluginName) {\n        return plugins[pluginName];\n    };\n\n    t.list = function() {\n        return Object.keys(plugins);\n    };\n\n    if (init) {\n        t.extend(init);\n    }\n}\n\n//\n// Uncomment "assert(...)" to use this:\n//\n\nfunction assert(x) { if (!x) throw new Error("assertion failed"); }\n\nfunction getEs5Globals() {\n    // Package the ECMAScript 5 Global Object properties so that\n    // careful users can provide a safer-seeming copy of them.  XXX If\n    // you want to use this, consider auditing PluginContainer and\n    // JsDispatch, too.\n    return {\n        NaN                : NaN,\n        Infinity           : Infinity,\n        undefined          : undefined,\n        eval               : eval,\n        parseInt           : parseInt,\n        parseFloat         : parseFloat,\n        isNaN              : isNaN,\n        isFinite           : isFinite,\n        decodeURI          : decodeURI,\n        decodeURIComponent : decodeURIComponent,\n        encodeURI          : encodeURI,\n        encodeURIComponent : encodeURIComponent,\n        Object             : Object,\n        Function           : Function,\n        Array              : Array,\n        String             : String,\n        Boolean            : Boolean,\n        Number             : Number,\n        Date               : Date,\n        RegExp             : RegExp,\n        Error              : Error,\n        EvalError          : EvalError,\n        RangeError         : RangeError,\n        ReferenceError     : ReferenceError,\n        SyntaxError        : SyntaxError,\n        TypeError          : TypeError,\n        URIError           : URIError,\n        Math               : Math,\n        JSON               : JSON\n    };\n}\n\nfunction implementUncurry(plugins) {\n    var g = plugins.get("es5globals");\n    var api = g.Object.create(null);\n\n    /*\n        uncurry(func) returns a function equivalent to\n\n        > function(arg...) { return func.call(arg...); }\n\n        but not relying on func or its prototype having a "call"\n        property.  The point is to make library code behave the same\n        after arbitrary code runs, possibly improving security and\n        performance.\n\n        http://wiki.ecmascript.org/doku.php?id=conventions:safe_meta_programming\n    */\n    api.uncurry = g.Function.prototype.bind.bind(g.Function.prototype.call);\n    return api;\n}\n\n/*\n    Function: defineGenericFunctions(plugins)\n    Creates the generic functions of number subtypes called by\n    higher-level library code.\n\n    The bulk of the internal/plugin API consists of these functions.\n    Their interfaces are optimized for ease of implementation and for\n    use in implementing the library.  By contrast, the Scheme library\n    strives more for interface stability and convenience of use.\n\n    For example, the public subtraction function, <fn["-"]>, accepts\n    one or more arguments, converts them from native types if\n    necessary, and subtracts all but the first from the first, unless\n    there is only one, in which case it negates it.  The library\n    converts all that into calls to <subtract>, with exactly two\n    arguments, both guaranteed to be Scheme numbers, or <negate> as\n    the case may be.\n\n    Input:\n\n    *plugins* shall be a <PluginContainer> containing *Dispatch*, a\n    <JsDispatch> object.  <defineGenericFunctions> calls the\n    *defGeneric* method of *Dispatch* to create each generic function.\n\n    Functions:\n\n    toSchemeNumber - see <implementSchemeNumber>\n\n    numberToString - generic function(schemeNumber, radix, precision)\n    Equivalent to <fn["number->string"]> but with *radix* and\n    *precision* as native numbers.\n\n    isExact - generic function(schemeNumber)\n    "exact?"\n\n    isInexact - generic function(schemeNumber)\n    "inexact?"\n\n    isComplex - generic function(schemeNumber)\n    "complex?"\n\n    isReal - generic function(schemeNumber)\n    "real?"\n\n    isRational - generic function(schemeNumber)\n    "rational?"\n\n    isInteger - generic function(schemeNumber)\n    "integer?"\n\n    isZero - generic function(schemeNumber)\n    "zero?"\n\n    toExact - generic function(schemeNumber)\n    "exact"\n\n    toInexact - generic function(schemeNumber)\n    "inexact"\n\n    negate - generic function(schemeNumber)\n    Returns the argument\'s additive inverse, -*schemeNumber*.\n\n    reciprocal - generic function(schemeNumber)\n    Return the argument\'s multiplicative inverse, 1 / *schemeNumber*.\n\n    eq - generic function(schemeNumber, schemeNumber)\n    "="\n\n    ne - generic function(schemeNumber, schemeNumber)\n    Returns true if, and only if, the arguments are *not* equal in the\n    sense of Scheme\'s "=".\n\n    add - generic function(schemeNumber, schemeNumber)\n    Returns the sum of the two arguments.\n\n    subtract - generic function(schemeNumber1, schemeNumber2)\n    Returns the difference *schemeNumber1* - *schemeNumber2*.\n\n    multiply - generic function(schemeNumber, schemeNumber)\n    Returns the product of the two arguments.\n\n    divide - generic function(schemeNumber1, schemeNumber2)\n    Returns the quotient *schemeNumber1* / *schemeNumber2*.\n\n    square - generic function(schemeNumber)\n    Returns the argument\'s square.\n\n    realPart - generic function(complex)\n    "real-part"\n\n    imagPart - generic function(complex)\n    "imag-part"\n\n    expt - generic function(schemeNumber, integer)\n    As in Scheme.\n\n    expt - generic function(complex, complex)\n    As in Scheme.\n\n    exp - generic function(complex)\n    As in Scheme.\n\n    magnitude - generic function(complex)\n    As in Scheme.\n\n    angle - generic function(complex)\n    As in Scheme.\n\n    sqrt - generic function(complex)\n    As in Scheme.\n\n    log - generic function(complex)\n    Single-argument *log* as in Scheme.\n\n    asin - generic function(complex)\n    As in Scheme.\n\n    acos - generic function(complex)\n    As in Scheme.\n\n    atan - generic function(complex)\n    Single-argument *atan* as in Scheme.\n\n    sin - generic function(complex)\n    As in Scheme.\n\n    cos - generic function(complex)\n    As in Scheme.\n\n    tan - generic function(complex)\n    As in Scheme.\n\n    SN_isFinite - generic function(real)\n    "finite?"\n\n    SN_isInfinite - generic function(real)\n    "infinite?"\n\n    SN_isNaN - generic function(real)\n    "nan?"\n\n    isUnit - generic function(real)\n    Returns true if its argument equals 1 or -1.\n\n    abs - generic function(real)\n    As in Scheme.\n\n    isPositive - generic function(real)\n    "positive?"\n\n    isNegative - generic function(real)\n    "negative?"\n\n    sign - generic function(real)\n    Returns native -1 if *real* is negative, 0 if zero, or 1 if positive.\n\n    floor - generic function(real)\n    As in Scheme.\n\n    ceiling - generic function(real)\n    As in Scheme.\n\n    truncate - generic function(real)\n    As in Scheme.\n\n    round - generic function(real)\n    As in Scheme.\n\n    compare - generic function(real1, real2)\n    Returns the <sign> of the difference <real1 - real2>.\n\n    gt - generic function(real, real)\n    ">"\n\n    lt - generic function(real, real)\n    "<"\n\n    ge - generic function(real, real)\n    ">="\n\n    le - generic function(real, real)\n    "<="\n\n    divAndMod - generic function(real, real)\n    "div-and-mod"\n\n    div - generic function(real, real)\n    As in Scheme.\n\n    mod - generic function(real, real)\n    As in Scheme.\n\n    atan2 - generic function(real, real)\n    Equivalent to *atan* with two arguments in Scheme.\n\n    numerator - generic function(rational)\n    As in Scheme.\n\n    denominator - generic function(rational)\n    As in Scheme.\n\n    isEven - generic function(exactInteger)\n    "even?"\n\n    isOdd - generic function(exactInteger)\n    "odd?"\n\n    exp10 - generic function(significand, exponent)\n    Both arguments are exact integers.  Returns an exact integer equal\n    to the *significand* times ten to the *exponent*.\n\n    gcdNonnegative - generic function(exactInteger, exactInteger)\n    Both arguments are non-negative, exact integers.  <gcdNonnegative>\n    returns their greatest common divisor (GCD).\n\n    divideReduced - generic function(numerator, denominator)\n    Both arguments are exact, relatively prime integers, and\n    *denominator* is greater than zero.  <divideReduced> returns an\n    exact rational equal to *numerator* divided by *denominator*.\n*/\n\nfunction defineGenericFunctions(plugins) {\n    "use strict";\n    var g = plugins.get("es5globals");\n    var disp = plugins.get("Dispatch");\n    var api = g.Object.create(null);\n\n    function def(name, ndisp, nargs) {\n        api[name] = disp.defGeneric(name, ndisp, nargs);\n    }\n\n    def("toSchemeNumber", 1);\n    def("numberToString", 1, 3);  // 2nd and 3rd args native\n    def("isExact", 1);\n    def("isInexact", 1);\n\n    def("isComplex", 1);\n    def("isReal", 1);\n    def("isRational", 1);\n    def("isInteger", 1);\n    def("isZero", 1);\n\n    def("toExact", 1);\n    def("toInexact", 1);\n    def("negate", 1);\n    def("reciprocal", 1);\n\n    def("eq", 2);\n    def("ne", 2);\n\n    def("add", 2);\n    def("subtract", 2);\n    def("multiply", 2);\n    def("divide", 2);\n\n    def("square", 1);\n\n    def("realPart", 1);\n    def("imagPart", 1);\n    def("magnitude", 1);\n    def("angle", 1);\n    def("conjugate", 1);\n\n    def("expt", 2);\n\n    def("exp", 1);\n    def("sqrt", 1);\n\n    def("log", 1);\n    def("asin", 1);\n    def("acos", 1);\n    def("atan", 1);\n\n    def("sin", 1);\n    def("cos", 1);\n    def("tan", 1);\n\n    def("SN_isFinite", 1);\n    def("SN_isInfinite", 1);\n    def("SN_isNaN", 1);\n\n    def("isUnit", 1);\n    def("abs", 1);\n    def("isPositive", 1);\n    def("isNegative", 1);\n    def("sign", 1);\n    def("floor", 1);\n    def("ceiling", 1);\n    def("truncate", 1);\n    def("round", 1);\n\n    def("compare", 2);\n    def("gt", 2);\n    def("lt", 2);\n    def("ge", 2);\n    def("le", 2);\n    def("divAndMod", 2);\n    def("div", 2);\n    def("mod", 2);\n    def("atan2", 2);\n\n    def("numerator", 1);\n    def("denominator", 1);\n    def("numeratorAndDenominator", 1);\n\n    def("isEven", 1);\n    def("isOdd", 1);\n    def("exactIntegerSqrt", 1);\n    def("exp10", 1, 2);      // 2nd arg exact integer\n    def("gcdNonnegative", 2);\n    def("divideReduced", 2);\n\n    def("bitwiseNot", 1);\n    def("bitwiseAnd", 2);\n    def("bitwiseIor", 2);\n    def("bitwiseXor", 2);\n    def("bitCount", 1);\n    def("bitLength", 1);\n    def("firstBitSet", 1);\n    def("isBitSet", 1, 2);  // 2nd arg convertible to index\n    def("copyBit", 1, 3);   // 2nd arg convertible to index; 3rd arg boolean\n    def("bitField", 1, 3);\n    def("copyBitField", 2, 4);\n    def("bitShift", 1, 2);\n    def("rotateBitField", 1, 4);\n    def("reverseBitField", 1, 3);\n\n    return api;\n}\n\nfunction defineSchemeNumberType(plugins) {\n    "use strict";\n    var g = plugins.get("es5globals");\n    var _NaN = g.NaN;\n    var api = g.Object.create(null);\n    var numberToString = plugins.get("numberToString");\n    var disp = plugins.get("Dispatch");\n\n    function SchemeNumberType(){}\n\n    // Inherit from Number so that "x instanceof Number" holds.\n    // But then override the standard methods, which are compatible\n    // only with native Number objects.\n\n    SchemeNumberType.prototype = new Number();\n\n    // Good defaults.\n    function genericToString(radix) {\n        if (numberToString)\n            return numberToString(this, radix);\n        return "[object SchemeNumber]";\n    }\n    function genericToLocaleString() {\n        return genericToString();\n    }\n    function retNaN() {\n        return _NaN;\n    }\n\n    // Bad default.\n    function genericFormatter() {\n        if (numberToString)\n            return numberToString(this);\n        return "SchemeNumber";\n    }\n\n    SchemeNumberType.prototype.toFixed        = genericFormatter;\n    SchemeNumberType.prototype.toExponential  = genericFormatter;\n    SchemeNumberType.prototype.toPrecision    = genericFormatter;\n    SchemeNumberType.prototype.toString       = genericToString;\n    SchemeNumberType.prototype.toLocaleString = genericToLocaleString;\n    SchemeNumberType.prototype.valueOf        = retNaN;\n\n    disp.defClass("SchemeNumber", { ctor: SchemeNumberType });\n\n    api.SchemeNumberType         = SchemeNumberType;\n    return api;\n}\n\n/*\n    Function: defineDebugFunction(plugins)\n    Creates a generic function, *debug*, for inspecting number objects.\n\n    Input:\n\n    *plugins* shall be a <PluginContainer> containing the following\n    element.\n\n    Dispatch - a <JsDispatch> object.\n    <defineDebugFunction> calls the *Dispatch* object\'s *defGeneric*\n    method to create the *debug* function, and calls the resulting\n    function\'s *def* method with class name "SchemeNumber" to define a\n    generic implementation of *debug*.\n\n    Output:\n\n    debug - generic function(schemeNumber) -> string\n    Applications must not rely on the returned string\'s format.\n    Number implementations should specialize this function to provide\n    internal details of use during development.  Developers may obtain\n    this function via *SchemeNumber.plugins.get("debug")*.  Example:\n\n    > SchemeNumber.plugins.get("debug")(SchemeNumber(10))  // "EINative(10)"\n\n    See Also: <JsDispatch>\n*/\nfunction defineDebugFunction(plugins) {\n    "use strict";\n    var g                = plugins.get("es5globals");\n    var uncurry          = plugins.get("uncurry");\n    var disp             = plugins.get("Dispatch");\n    var SchemeNumberType = plugins.get("SchemeNumberType");\n    var Object_toString  = uncurry(g.Object.prototype.toString);\n    var api = g.Object.create(null);\n\n    // Generic default for classes that don\'t specialize debug.\n    function SchemeNumber_debug() {\n        var t;\n        try { t = this.toString(); }\n        catch (e) {\n            try { t = Object_toString(this); }\n            catch (e) { t = "?"; }\n        }\n        return "SchemeNumber(" + t + ")";\n    }\n\n    api.debug = disp.defGeneric("debug", 1);\n    api.debug.def(SchemeNumberType, SchemeNumber_debug);\n\n    return api;\n}\n\n\n/*\n    Function: implementCoreLibrary(plugins)\n    Creates the plugins required by Scheme functions and a few others.\n\n    Input:\n\n    *plugins* shall be a <PluginContainer> containing the items listed\n    below.  All may be added after the call to <implementCoreLibrary>\n    but before any use of its results.  When changes to plugins\n    produce changes in non-function results (such as *ZERO* and\n    *ONE*), the library broadcasts the changes via the\n    <PluginContainer.onChange> event.\n\n    SchemeNumber - function(any)\n    The <SchemeNumber> object as returned by\n    <implementSchemeNumber(plugins)>.\n\n    nativeToExactInteger - function(integer)\n    *integer* is a native ECMAScript number of integer value.\n    <nativeToExactInteger> returns an exact Scheme number whose value\n    equals *integer*.\n\n    nativeToInexact - function(number)\n    *number* is a native ECMAScript number, possibly infinite or\n    *NaN*.  <nativeToInexact> returns an inexact Scheme number\n    approximating its argument.\n\n    parseExactInteger - function(sign, string, radix)\n    *sign* is the native number 1 or -1.  *radix* is the native number\n    2, 8, 10, or 16.  <parseExactInteger> must be a function returning\n    a Scheme number equal to *sign* times the result of parsing\n    *string* as a positive, unprefixed, exact integer in the given\n    radix.\n\n    parseInexact - function(sign, string)\n    *sign* is the native number 1 or -1.  <parseExact> must be a\n    function returning a Scheme number equal to *sign* times the\n    result of parsing *string* as a positive, unprefixed, decimal,\n    inexact, real number.\n\n    exactRectangular - function(x, y)\n    *x* and *y* are exact reals, *y* non-zero.  <exactRectangular>\n    returns an exact complex equal to *x* + (i * *y*).\n\n    inexactRectangular - function(x, y)\n    *x* and *y* are inexact reals.  <inexactRectangular> returns an\n    inexact complex equal to *x* + (i * *y*).\n\n    exactPolar - function(r, theta)\n    *r* and *theta* are exact reals.  <exactPolar> returns an exact\n    complex equal to *r* * exp(i * *theta*).\n\n    inexactPolar - function(r, theta)\n    *r* and *theta* are inexact reals.  <inexactPolar> returns an\n    inexact complex equal to *r* * exp(i * *theta*).\n\n    Output:\n\n    <implementCoreLibrary> returns an object with the following\n    properties.\n\n    ZERO - the exact integer *0*.\n\n    ONE - the exact integer *1*.\n\n    TWO - the exact integer *2*.\n\n    MINUS_ONE - the exact integer *-1*.\n\n    INEXACT_ZERO - the inexact integer *0.0*.\n\n    INEXACT_ONE - the inexact integer *1.0*.\n\n    PI - the inexact real number pi.\n\n    INFINITY - the inexact real number *+inf.0*.\n\n    MINUS_INFINITY - the inexact real number *-inf.0*.\n\n    NAN - the inexact real number *+nan.0*.\n\n    I - the exact complex unit *i*.\n\n    MINUS_I - the exact complex unit *-i*.\n\n    raise - function(conditionType, message, irritant...)\n    This *raise* simply calls the user-overridable\n    <SchemeNumber.raise> but enforces the contract not to return.\n\n    defaultRaise - function(conditionType, message, irritant...)\n    Throws an Error describing the arguments.\n\n    raiseDivisionByExactZero - function()\n    Raises an exception as specified by Scheme to report division by\n    exact zero.\n\n    isNumber - function(x)\n    Returns true if *x* is a Scheme number.\n\n    assertReal - function(x)\n    Returns *x* if *x* is a real Scheme number, otherwise raises an\n    exception as specified by Scheme for invalid argument type.\n\n    toReal - function(x)\n    Converts *x* to a Scheme number and behaves as if by returning\n    *assertReal(x)*.\n\n    assertInteger - function(x)\n    Returns *x* if *x* is a Scheme integer, otherwise raises an\n    exception as specified by Scheme for invalid argument type.\n\n    toInteger - function(x)\n    Converts *x* to a Scheme number and behaves as if by returning\n    *assertInteger(x)*.\n\n    assertExact - function(x)\n    Returns *x* if *x* is an exact Scheme number, otherwise raises an\n    exception as specified by Scheme for invalid argument type.\n\n    stringToNumber - function(string, radix, exact)\n    <stringToNumber> returns the Scheme number whose external\n    representation is *string* with added prefixes corresponding to\n    either or both of *radix* and *exact*, if defined.\n\n    *s* should be the external representation of a Scheme number, such\n    as "2/3" or "#e1.1@-2d19".  If *s* does not represent a Scheme\n    number, <stringToNumber> returns *false*.\n\n    If *radix* is given, it must be either 2, 8, 10, or 16, and *s*\n    must not contain a radix prefix.  The function behaves as if *s*\n    did contain the prefix corresponding to *radix*.\n\n    If *exact* is given, it must have type "boolean", and *s* must not\n    contain an exactness prefix.  The function behaves as if *s*\n    contained the corresponding prefix ("#e" if *exact* is true, "#i"\n    if false).\n\n    truncateToPrecision -\n\n    XXX documentation incomplete.\n*/\nfunction implementCoreLibrary(plugins) {\n    "use strict";\n\n    // Abstract types, generic functions, and the SchemeNumber object.\n    // XXX Could remove unused items.\n    var SchemeNumber, toSchemeNumber, SchemeNumberType, Complex, Real,\n        InexactReal, ExactReal, ExactRational, ExactInteger,\n        numberToString, isExact, isInexact, isComplex, isReal,\n        isRational, isInteger, isZero, toExact, toInexact, negate,\n        reciprocal, eq, ne, add, subtract, multiply, divide, square,\n        realPart, imagPart, expt, expt, exp, magnitude, angle, sqrt,\n        log, asin, acos, atan, sin, cos, tan, SN_isFinite,\n        SN_isInfinite, SN_isNaN, isUnit, abs, isPositive, isNegative,\n        sign, floor, ceiling, truncate, round, compare, gt, lt, ge,\n        le, divAndMod, div, mod, atan2, numerator, denominator,\n        numeratorAndDenominator,\n        isEven, isOdd, exp10, gcdNonnegative, divideReduced;\n\n    SchemeNumber             = plugins.get("SchemeNumber");\n\n    SchemeNumberType         = plugins.get("SchemeNumberType");\n    Complex                  = plugins.get("Complex");\n    Real                     = plugins.get("Real");\n    InexactReal              = plugins.get("InexactReal");\n    ExactReal                = plugins.get("ExactReal");\n    ExactRational            = plugins.get("ExactRational");\n    ExactInteger             = plugins.get("ExactInteger");\n\n    toSchemeNumber           = plugins.get("toSchemeNumber");\n    numberToString           = plugins.get("numberToString");\n    isExact                  = plugins.get("isExact");\n    isInexact                = plugins.get("isInexact");\n    isComplex                = plugins.get("isComplex");\n    isReal                   = plugins.get("isReal");\n    isRational               = plugins.get("isRational");\n    isInteger                = plugins.get("isInteger");\n    isZero                   = plugins.get("isZero");\n    toExact                  = plugins.get("toExact");\n    toInexact                = plugins.get("toInexact");\n    negate                   = plugins.get("negate");\n    reciprocal               = plugins.get("reciprocal");\n    eq                       = plugins.get("eq");\n    ne                       = plugins.get("ne");\n    add                      = plugins.get("add");\n    subtract                 = plugins.get("subtract");\n    multiply                 = plugins.get("multiply");\n    divide                   = plugins.get("divide");\n    square                   = plugins.get("square");\n    realPart                 = plugins.get("realPart");\n    imagPart                 = plugins.get("imagPart");\n    expt                     = plugins.get("expt");\n    expt                     = plugins.get("expt");\n    exp                      = plugins.get("exp");\n    magnitude                = plugins.get("magnitude");\n    angle                    = plugins.get("angle");\n    sqrt                     = plugins.get("sqrt");\n    log                      = plugins.get("log");\n    asin                     = plugins.get("asin");\n    acos                     = plugins.get("acos");\n    atan                     = plugins.get("atan");\n    sin                      = plugins.get("sin");\n    cos                      = plugins.get("cos");\n    tan                      = plugins.get("tan");\n    SN_isFinite              = plugins.get("SN_isFinite");\n    SN_isInfinite            = plugins.get("SN_isInfinite");\n    SN_isNaN                 = plugins.get("SN_isNaN");\n    isUnit                   = plugins.get("isUnit");\n    abs                      = plugins.get("abs");\n    isPositive               = plugins.get("isPositive");\n    isNegative               = plugins.get("isNegative");\n    sign                     = plugins.get("sign");\n    floor                    = plugins.get("floor");\n    ceiling                  = plugins.get("ceiling");\n    truncate                 = plugins.get("truncate");\n    round                    = plugins.get("round");\n    compare                  = plugins.get("compare");\n    gt                       = plugins.get("gt");\n    lt                       = plugins.get("lt");\n    ge                       = plugins.get("ge");\n    le                       = plugins.get("le");\n    divAndMod                = plugins.get("divAndMod");\n    div                      = plugins.get("div");\n    mod                      = plugins.get("mod");\n    atan2                    = plugins.get("atan2");\n    numerator                = plugins.get("numerator");\n    denominator              = plugins.get("denominator");\n    numeratorAndDenominator  = plugins.get("numeratorAndDenominator");\n    isEven                   = plugins.get("isEven");\n    isOdd                    = plugins.get("isOdd");\n    exp10                    = plugins.get("exp10");\n    gcdNonnegative           = plugins.get("gcdNonnegative");\n    divideReduced            = plugins.get("divideReduced");\n\n    // Functions to be provided by number implementations.\n    var nativeToInexact, parseInexact;\n    var parseExactInteger, nativeToExactInteger;\n    var divideReducedNotByOne;\n    var exactRectangular, inexactRectangular, exactPolar, inexactPolar;\n\n    // Constants to be defined here once we have the necessaries.\n    var ZERO, ONE, TWO, MINUS_ONE, I, MINUS_I;\n    var INEXACT_ZERO, INEXACT_ONE, PI, INFINITY, MINUS_INFINITY, NAN;\n\n    // Imports from ECMAScript.\n    var g                = plugins.get("es5globals");\n    var uncurry          = plugins.get("uncurry");\n    var Array_slice      = uncurry(g.Array.prototype.slice);\n    var Array_join       = uncurry(g.Array.prototype.join);\n    var Number_toString  = uncurry(g.Number.prototype.toString);\n    var String_indexOf   = uncurry(g.String.prototype.indexOf);\n    var String_substring = uncurry(g.String.prototype.substring);\n    var String_replace   = uncurry(g.String.prototype.replace);\n    var RegExp_test      = uncurry(g.RegExp.prototype.test);\n\n    var Math_LN10    = g.Math.LN10;\n    var Math_LN2     = g.Math.LN2;\n    var Math_PI      = g.Math.PI;\n    var Math_abs     = g.Math.abs;\n    var Math_floor   = g.Math.floor;\n    var Math_pow     = g.Math.pow;\n    var _LN2         = g.Math.LN2;\n    var _LN10        = g.Math.LN10;\n    var _PI          = g.Math.PI;\n    var _undefined   = g.undefined;\n    var _Infinity    = g.Infinity;\n    var _NaN         = g.NaN;\n    var _parseInt    = g.parseInt;\n    var _isNaN       = g.isNaN;\n    var _isFinite    = g.isFinite;\n\n    var api = g.Object.create(null);\n\n    function onPluginsChanged(plugins, changed) {\n        nativeToExactInteger     = plugins.get("nativeToExactInteger");\n        parseExactInteger        = plugins.get("parseExactInteger");\n        nativeToInexact          = plugins.get("nativeToInexact");\n        parseInexact             = plugins.get("parseInexact");\n        divideReducedNotByOne    = plugins.get("divideReducedNotByOne");\n        exactRectangular         = plugins.get("exactRectangular");\n        inexactRectangular       = plugins.get("inexactRectangular");\n        exactPolar               = plugins.get("exactPolar");\n        inexactPolar             = plugins.get("inexactPolar");\n\n        function getComplexConstant(x, y) {\n            try {\n                return exactRectangular(nativeToExactInteger(x),\n                                        nativeToExactInteger(y));\n            }\n            catch (e) {\n                return _undefined;\n            }\n        }\n\n        var exts = g.Object.create(null);\n        if (changed.nativeToExactInteger || changed.exactRectangular) {\n            I       = exts.I       = getComplexConstant(0, 1);\n            MINUS_I = exts.MINUS_I = getComplexConstant(0, -1);\n        }\n        if (changed.nativeToExactInteger) {\n            ZERO      = exts.ZERO      = nativeToExactInteger(0);\n            ONE       = exts.ONE       = nativeToExactInteger(1);\n            TWO       = exts.TWO       = nativeToExactInteger(2);\n            MINUS_ONE = exts.MINUS_ONE = nativeToExactInteger(-1);\n        }\n        if (changed.nativeToInexact) {\n            INEXACT_ZERO   = exts.INEXACT_ZERO   = nativeToInexact(0);\n            INEXACT_ONE    = exts.INEXACT_ONE    = nativeToInexact(1);\n            PI             = exts.PI             = nativeToInexact(Math_PI);\n            INFINITY       = exts.INFINITY       = nativeToInexact(_Infinity);\n            MINUS_INFINITY = exts.MINUS_INFINITY = nativeToInexact(-_Infinity);\n            NAN            = exts.NAN            = nativeToInexact(_NaN);\n        }\n        // XXX should not recurse into extend().  Should return exts\n        // here and make extend() loop.\n        plugins.extend(exts);\n    }\n    plugins.onChange.subscribe(onPluginsChanged);\n    onPluginsChanged(plugins, {});\n\n    function retFalse()   { return false; }\n    function retTrue()    { return true;  }\n    function retThis()    { return this; }\n    function retZero()    { return ZERO; }\n    function retOne()     { return ONE; }\n    function retFirst(a)  { return a; }\n\n    function makeRectangular(x, y) {\n        if (isInexact(x))\n            return inexactRectangular(x, toInexact(y));\n        if (isInexact(y))\n            return inexactRectangular(toInexact(x), y);\n        return exactRectangular(x, y);\n    }\n\n    function makePolar(x, y) {\n        if (isInexact(x))\n            return inexactPolar(x, toInexact(y));\n        if (isInexact(y))\n            return inexactPolar(toInexact(x), y);\n        return exactPolar(x, y);\n    }\n\n    function defaultRaise(conditionType, message, irritant) {\n        var i, arg, msg = "SchemeNumber: " + conditionType + ": " + message;\n        if (arguments.length > 2) {\n            msg += ": ";\n            i = 2;\n            while (true) {\n                arg = arguments[i];\n                try { msg += numberToString(arg); }\n                catch (e) {\n                    try { msg += arg; }\n                    catch (e) { msg += "?"; }\n                }\n                i++;\n                if (i === arguments.length)\n                    break;\n                msg += ", ";\n            }\n        }\n        throw new g.Error(msg);\n    }\n\n    /*\n        raise - function(conditionType, message, irritants...)\n        Forwards its arguments to <SchemeNumber.raise> and handles\n        errors in that function, namely returning when it shouldn\'t.\n    */\n    function raise() {\n        var args = Array_slice(arguments);\n\n        // Call the exception hook.\n        SchemeNumber.raise.apply(SchemeNumber, args);\n\n        // Oops, it returned.  Fall back to our known good raiser.\n        defaultRaise.apply(this, args);\n    }\n\n    function raiseDivisionByExactZero() {\n        raise("&assertion", "division by exact zero");\n    }\n\n    //\n    // For (rnrs base (6)) i.e. SchemeNumber.fn.  Could perhaps move\n    // to a library and get via onPluginsChanged.\n    //\n\n    // Compute a real that had a |p attached.\n    // See the second half of R6RS Section 4.2.8 and also\n    // http://www.mail-archive.com/r6rs-discuss@lists.r6rs.org/msg01676.html.\n\n    // This could be greatly optimized for native numbers using\n    // numberToBinary, but I have no use case, so I went with a slow,\n    // (hopefully) correct version.\n    function truncateToPrecision(x, precision, exact) {\n\n        if (x === false || !isReal(x))\n            lose();\n\n        if (!isZero(x)) {\n            var xabs = abs(x);\n\n            var shift = precision - Math_floor(log(xabs) / Math_LN2) - 1;\n            var scale = expt(TWO, nativeToExactInteger(Math_abs(shift)));\n            if (shift < 0)\n                scale = reciprocal(scale);\n            var shifted = multiply(xabs, scale);\n\n            // Correct for log() imprecision.\n            var denom = expt(TWO, nativeToExactInteger(precision));\n            while (ge(shifted, denom)) {\n                shifted = divide(shifted, TWO);\n                scale = divide(scale, TWO);\n            }\n            for (var twiceShifted = add(shifted, shifted);\n                 lt(twiceShifted, denom);\n                 twiceShifted = add(shifted, shifted)) {\n                shifted = twiceShifted;\n                scale = add(scale, scale);\n            }\n\n            // 0.5 <= shifted/denom < 1.\n            var rounded = divide(round(shifted), scale);\n            if (isNegative(x))\n                rounded = negate(rounded);\n            x = rounded;\n        }\n\n        // Then make it inexact unless there is #e.\n        if (!exact)\n            x = toInexact(x);\n\n        return x;\n    }\n\n    function assertReal(x) {\n        if (!isReal(x))\n            raise("&assertion", "not a real number", x);\n        return x;\n    }\n\n    function toReal(x) {\n        x = SchemeNumber(x);\n        isReal(x) || assertReal(x);\n        return x;\n    }\n\n    function assertRational(q) {\n        if (!isRational(q))\n            raise("&assertion", "not a rational number", q);\n        return q;\n    }\n\n    function toRational(q) {\n        q = SchemeNumber(q);\n        isRational(q) || assertRational(q);\n        return q;\n    }\n\n    function assertInteger(n) {\n        n = SchemeNumber(n);\n        if (!isInteger(n))\n            raise("&assertion", "not an integer", n);\n        return n;\n    }\n\n    function toInteger(n) {\n        n = SchemeNumber(n);\n        isInteger(n) || assertInteger(n);\n        return n;\n    }\n\n    function assertExact(z) {\n        if (isInexact(z))\n            raise("&assertion", "inexact number", z);\n        return z;\n    }\n\n    function isNumber(x) {\n        return x instanceof SchemeNumberType;\n    }\n\n    //\n    // For (rnrs base (6)) i.e. SchemeNumber.fn.\n    // Specifically, fn["string->number"] and SchemeNumber("...")\n    //\n\n    // How to split a rectangular literal into real and imaginary components:\n    var decimalComplex = /^(.*[^a-zA-Z]|)([-+].*)i$/;\n    var radixComplex = /^(.*)([-+].*)i$/;\n\n    var nanInfPattern = /^[-+](nan|inf)\\.0$/;\n    var exponentMarkerPattern = /[eEsSfFdDlL]/;\n    var decimal10Pattern =\n        /^([0-9]+\\.?|[0-9]*\\.[0-9]+)([eEsSfFdDlL][-+]?[0-9]+)?$/;\n\n    var uintegerPattern = {\n        2: /^[01]+$/, 8: /^[0-7]+$/, 10: /^[0-9]+$/, 16: /^[0-9a-fA-F]+$/\n    };\n\n    var PARSE_ERROR = new g.Object();\n\n    function stringToNumber(s, radix, exact) {\n        function lose() {\n            throw PARSE_ERROR;\n        }\n        function check(z) {\n            return z === false ? lose() : z;\n        }\n        function setExact(value) {\n            if (exact !== _undefined) lose();\n            exact = value;\n        }\n        function setRadix(value) {\n            if (radix) lose();\n            radix = value;\n        }\n        function parseUinteger(s, sign) {\n            if (!RegExp_test(uintegerPattern[radix], s))\n                lose();\n\n            if (exact === false) {\n                if (radix === 10)\n                    return parseInexact(sign, s);\n                return toInexact(parseExactInteger(sign, s, radix));\n            }\n            return parseExactInteger(sign, s, radix);\n        }\n        function parseReal(s) {\n            if (RegExp_test(nanInfPattern, s)) {\n                if (exact)\n                    lose();\n                switch (s) {\n                case "+inf.0": return INFINITY;\n                case "-inf.0": return MINUS_INFINITY;\n                default: return NAN;\n                }\n            }\n\n            var sign = 1;\n            switch (s[0]) {\n            case \'-\': sign = -1;  // fall through\n            case \'+\': s = String_substring(s, 1);\n            }\n\n            var slash = String_indexOf(s, \'/\');\n            if (slash != -1)\n                return divide(\n                    parseUinteger(String_substring(s, 0, slash), sign),\n                    parseUinteger(String_substring(s, slash + 1), 1));\n\n            if (radix !== 10)\n                return parseUinteger(s, sign);\n\n            var pipe = String_indexOf(s, \'|\');\n            if (pipe !== -1) {\n\n                // WHOA!!!  Explicit mantissa width!  Somebody really\n                // cares about correctness.  However, I haven\'t got all\n                // day, so execution speed loses.\n\n                var afterPipe = String_substring(s, pipe + 1);\n                if (!RegExp_test(uintegerPattern[10], afterPipe))\n                    lose();\n\n                s = String_substring(s, 0, pipe);\n                var precision = _parseInt(afterPipe, 10);\n\n                if (precision === 0)\n                    s = "0.0";\n                else if (precision < 53)\n                    return check(\n                        truncateToPrecision(stringToNumber(s, radix, true),\n                                            precision, exact));\n            }\n\n            // We have only one floating point width.\n            s = String_replace(s, exponentMarkerPattern, \'e\');\n\n            var dot = String_indexOf(s, \'.\');\n            var e = String_indexOf(s, \'e\');\n            if (dot === -1 && e === -1)\n                return parseUinteger(s, sign);\n\n            if (!RegExp_test(decimal10Pattern, s))\n                lose();\n\n            if (!exact)\n                return parseInexact(sign, s);\n\n            var integer = String_substring(s, 0, dot === -1 ? e : dot);\n            var exponent = ZERO;\n            var fraction;\n\n            if (e === -1)\n                fraction = String_substring(s, dot + 1);\n            else {\n                if (dot === -1)\n                    fraction = "";\n                else\n                    fraction = String_substring(s, dot + 1, e);\n                exponent = parseReal(String_substring(s, e + 1));\n            }\n\n            return exp10(parseExactInteger(sign, integer + fraction),\n                         subtract(exponent,\n                                  nativeToExactInteger(fraction.length)));\n        }\n        function parseComplex(s) {\n            var a = String_indexOf(s, \'@\');\n            if (a !== -1) {\n                var ret = makePolar(parseReal(String_substring(s, 0, a)),\n                                    parseReal(String_substring(s, a + 1)));\n                if (exact && isInexact(ret))\n                    // XXX I don\'t think this is right.  If Scheme\n                    // allows this, then by analogy, nothing requires\n                    // (numerator #e0.1) to equal 1.\n                    //ret = toExact(ret);\n                    ret = ret;  // ignore #e.\n                return ret;\n            }\n\n            if (s[s.length - 1] !== "i")\n                return parseReal(s);\n\n            if (s === "i") {\n                if (exact === false)\n                    return inexactRectangular(INEXACT_ZERO, INEXACT_ONE);\n                return I;\n            }\n            if (s === "-i") {\n                if (exact === false)\n                    return inexactRectangular(INEXACT_ZERO,\n                                              negate(INEXACT_ONE));\n                return MINUS_I;\n            }\n\n            var match = (radix === 10 ? decimalComplex : radixComplex).exec(s);\n            var x, y;\n            if (match) {\n                x = match[1];\n                y = match[2];\n                x = (x ? parseReal(x)\n                       : (exact === false ? INEXACT_ZERO : ZERO));\n                y = (y === "+" ? ONE\n                               : (y === "-" ? MINUS_ONE : parseReal(y)));\n            }\n            else {\n                // Could be, for example, "3i".\n                x = (exact === false ? INEXACT_ZERO : ZERO);\n                y = parseReal(String_substring(s, 0, s.length - 1));\n            }\n\n            return makeRectangular(x, y);\n        }\n\n        // Common cases first.\n        if (!radix || radix === 10) {\n            if (RegExp_test(/^-?[0-9]{1,15}$/, s)) {\n                if (exact === false)\n                    return nativeToInexact(_parseInt(s, 10));\n                return nativeToExactInteger(_parseInt(s, 10));\n            }\n        }\n\n        var i = 0;\n\n        try {\n            while (s[i] === "#") {\n                switch (s[i+1]) {\n                case \'i\': case \'I\': setExact(false); break;\n                case \'e\': case \'E\': setExact(true ); break;\n                case \'b\': case \'B\': setRadix( 2); break;\n                case \'o\': case \'O\': setRadix( 8); break;\n                case \'d\': case \'D\': setRadix(10); break;\n                case \'x\': case \'X\': setRadix(16); break;\n                default: return false;\n                }\n                i += 2;\n            }\n            radix = radix || 10;\n            return parseComplex(String_substring(s, i));\n        }\n        catch (e) {\n            if (e === PARSE_ERROR)\n                return false;\n            if (s == _undefined)\n                raise("&assertion", "missing argument");\n            throw e;\n        }\n    }\n\n    //\n    // End library function definitions.\n    //\n\n    api.I                        = I;\n    api.ZERO                     = ZERO;\n    api.ONE                      = ONE;\n    api.TWO                      = TWO;\n    api.MINUS_ONE                = MINUS_ONE;\n    api.INEXACT_ZERO             = INEXACT_ZERO;\n    api.INEXACT_ONE              = INEXACT_ONE;\n    api.PI                       = PI;\n    api.INFINITY                 = INFINITY;\n    api.MINUS_INFINITY           = MINUS_INFINITY;\n    api.NAN                      = NAN;\n\n    api.raise                    = raise;\n    api.defaultRaise             = defaultRaise;\n    api.raiseDivisionByExactZero = raiseDivisionByExactZero;\n    api.stringToNumber           = stringToNumber;\n    api.isNumber                 = isNumber;\n    api.assertReal               = assertReal;\n    api.toReal                   = toReal;\n    api.assertRational           = assertRational;\n    api.toRational               = toRational;\n    api.assertInteger            = assertInteger;\n    api.toInteger                = toInteger;\n    api.assertExact              = assertExact;\n\n    api.makeRectangular          = makeRectangular;\n    api.makePolar                = makePolar;\n\n    api.truncateToPrecision      = truncateToPrecision;\n\n    api.retFalse                 = retFalse;\n    api.retTrue                  = retTrue;\n    api.retThis                  = retThis;\n    api.retZero                  = retZero;\n    api.retOne                   = retOne;\n    api.retFirst                 = retFirst;\n\n    return api;\n}\n\n\n/*\n    Function: implementRnrsBase(plugins)\n    Creates and returns the <SchemeNumber.fn> function collection.\n\n    Input:\n\n    *plugins* shall be a <PluginContainer> containing the public\n    <SchemeNumber> object under the name *SchemeNumber*, as well as\n    the output of <defineGenericFunctions> and <implementCoreLibrary>.\n    The required plugins may be added between the call to\n    <implementRnrsBase> and the first use of its results.\n\n    About: Function list\n\n    All <Scheme functions> are specified by <R6RS at\n    http://www.r6rs.org/>.  In the list below, argument names indicate\n    applicable types as follows:\n\n    obj - any value\n    z - any Scheme number\n    x - a real number\n    y - a real number\n    q - a rational number (excludes infinities and NaN)\n    n - an integer\n    k - an exact, non-negative integer\n    radix - an exact integer, either 2, 8, 10, or 16\n    precision - an exact, positive integer\n\n    Functions: Scheme functions\n    Elements of <fn>.\n\n    Refer to the argument type key under <Function list>.\n\n    fn["number?"](obj)   - Returns true if *obj* is a Scheme number.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_440>.\n\n    fn["complex?"](obj)  - Returns true if *obj* is a Scheme complex number.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_442>.\n\n    fn["real?"](obj)     - Returns true if *obj* is a Scheme real number.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_444>.\n\n    fn["rational?"](obj) - Returns true if *obj* is a Scheme rational number.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_446>.\n\n    fn["integer?"](obj)  - Returns true if *obj* is a Scheme integer.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_448>.\n\n    fn["real-valued?"](obj) - Returns true if *obj* is a Scheme complex number\n                              and *fn["imag-part"](obj)* is zero.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_450>.\n\n    fn["rational-valued?"](obj) - Returns true if *obj* is real-valued and\n                                  *fn["real-part"](obj)* is rational.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_452>.\n\n    fn["integer-valued?"](obj)  - Returns true if *obj* is real-valued and\n                                  *fn["real-part"](obj)* is an integer.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_454>.\n\n    fn["exact?"](z)   - Returns true if *z* is exact.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_456>.\n\n    fn["inexact?"](z) - Returns true if *z* is inexact.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_458>.\n\n    fn.inexact(z) - Returns an inexact number equal to *z*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_460>.\n\n    fn.exact(z)   - Returns an exact number equal to *z*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_462>.\n\n    fn["eqv?"](obj1, obj2) - Returns true if *obj1 === obj2* or both arguments\n                             are Scheme numbers and behave identically.\n                             Specified by <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_428>.\n\n    fn["="](z, z, z...) - Returns true if all arguments are mathematically\n                          equal, though perhaps differing in exactness.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_464>.\n\n    fn["<"](x, x, x...) - Returns true if arguments increase monotonically.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_466>.\n\n    fn[">"](x, x, x...) - Returns true if arguments decrease monotonically.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_468>.\n\n    fn["<="](x, x, x...) - Returns true if arguments are monotonically\n                           nondecreasing.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_470>.\n\n    fn[">="](x, x, x...) - Returns true if arguments are monotonically\n                           nonincreasing.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_472>.\n\n    fn["zero?"](z)      - Returns true if *z* equals zero.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_474>.\n\n    fn["positive?"](x)  - Returns true if *x* is positive.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_476>.\n\n    fn["negative?"](x)  - Returns true if *x* is negative.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_478>.\n\n    fn["odd?"](n)       - Returns true if *n* is odd.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_480>.\n\n    fn["even?"](n)      - Returns true if *n* is even.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_482>.\n\n    fn["finite?"](x)    - Returns true if *x* is finite.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_484>.\n\n    fn["infinite?"](x)  - Returns true if *x* is plus or minus infinity.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_486>.\n\n    fn["nan?"](x)       - Returns true if *x* is a NaN.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_488>.\n\n    fn.max(x, x...)     - Returns the greatest argument.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_490>.\n\n    fn.min(x, x...)     - Returns the least argument.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_492>.\n\n    fn["+"](z...)       - Returns the sum of the arguments.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_494>.\n\n    fn["*"](z...)       - Returns the product of the arguments.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_496>.\n\n    fn["-"](z)          - Returns the negation of *z* (-*z*).\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_498>.\n\n    fn["-"](z1, z2...)  - Returns *z1* minus the sum of the number(s) *z2*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_500>.\n\n    fn["/"](z)          - Returns the reciprocal of *z* (1 / *z*).\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_502>.\n\n    fn["/"](z1, z2...)  - Returns *z1* divided by the product of the number(s)\n    *z2*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_504>.\n\n    fn.abs(x)           - Returns the absolute value of *x*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_506>.\n\n    fn["div-and-mod"](x, y) - Returns *fn.div(x, y)* and *fn.mod(x, y)*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_508>.\n\n    fn.div(x, y)        - Returns the greatest integer less than or equal to\n                          *x* / *y*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_510>.\n\n    fn.mod(x, y)        - Returns *x* - (*y* * fn.div(*x*, *y*)).\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_512>.\n\n    fn["div0-and-mod0"](x, y) - Returns *fn.div0(x, y)* and *fn.mod0(x, y)*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_514>.\n\n    fn.div0(x, y)       - Returns the integer nearest *x* / *y*, ties go lower.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_516>.\n\n    fn.mod0(x, y)       - Returns *x* - (*y* * fn.div0(*x*, *y*)).\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_518>.\n\n    fn.gcd(n...) - Returns the arguments\' greatest common non-negative divisor.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_520>.\n\n    fn.lcm(n...) - Returns the arguments\' least common positive multiple.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_522>.\n\n    fn.numerator(q)     - Returns *q* * *fn.denominator(q)*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_524>.\n\n    fn.denominator(q)   - Returns the smallest positive integer which when\n                          multiplied by *q* yields an integer.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_526>.\n\n    fn.floor(x)         - Returns the greatest integer not greater than *x*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_528>.\n\n    fn.ceiling(x)       - Returns the least integer not less than *x*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_530>.\n\n    fn.truncate(x)      - Returns the closest integer between 0 and *x*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_532>.\n\n    fn.round(x)         - Returns the closest integer to *x*, ties go even.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_534>.\n\n    fn.rationalize(x, y) - Returns the simplest fraction within *y* of *x*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_536>.\n\n    fn.exp(z)           - Returns e to the *z*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_540>.\n\n    fn.log(z)           - Returns the natural logarithm of *z*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_542>.\n\n    fn.log(z1, z2)      - Returns the base-*z2* logarithm of *z1*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_544>.\n\n    fn.sin(z)           - Returns the sine of *z*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_546>.\n\n    fn.cos(z)           - Returns the cosine of *z*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_548>.\n\n    fn.tan(z)           - Returns the tangent of *z*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_550>.\n\n    fn.asin(z)          - Returns a number whose sine is *z*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_552>.\n\n    fn.acos(z)          - Returns a number whose cosine is *z*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_554>.\n\n    fn.atan(z)          - Returns a number whose tangent is *z*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_556>.\n\n    fn.atan(y, x)       - Returns the angle that passes through *(x,y)*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_558>.\n\n    fn.sqrt(z)          - Returns the square root of *z*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_560>.\n\n    fn["exact-integer-sqrt"](k) - Returns maximal exact s and non-negative r\n                                  such that s*s + r = *k*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_562>.\n\n    fn.expt(z1, z2) - Returns *z1* to the power *z2*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_564>.\n\n    fn["make-rectangular"](x, y) - Returns the complex number *x + iy*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_566>.\n\n    fn["make-polar"](r, theta) - Returns the complex number with magnitude *r*\n                                 and angle *theta*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_568>.\n\n    fn["real-part"](z) - Returns x such that *z* = x + iy.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_570>.\n\n    fn["imag-part"](z) - Returns y such that *z* = x + iy.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_572>.\n\n    fn.magnitude(z)    - Returns the magnitude of *z*.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_574>.\n\n    fn.angle(z)        - Returns *fn.atan(y,x)* where *z* = x + iy.\n    Specified by: <R6RS at http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_576>.\n\n    Function: fn["number->string"](z)\n    Converts *z* to a string, base 10.\n\n    For exact *z*, *number->string* retains full precision.  Exact\n    fractions are expressed as numerator + "/" + denominator.\n    Examples:\n\n    > fn["number->string"](fn["string->number"]("#e1.2"))  // "6/5"\n    > fn["number->string"](fn["/"]("12", "-8"))            // "-3/2"\n\n    Infinities are "+inf.0" and "-inf.0".  NaN is "+nan.0".\n\n    The result always yields a number equal to *z* (in the sense of\n    <fn["eqv?"](obj1, obj2)>) when passed to\n    <fn["string->number"](string)>.\n\n    Specified by: <R6RS at\n    http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_578>\n\n    See Also: <fn["string->number"](string)>.\n\n    Function: fn["number->string"](z, radix)\n    Converts *z* to a string, base *radix*.\n    *radix* must be exact 2, 8, 10, or 16.\n\n    The output never contains an explicit radix prefix.\n\n    The result always yields a value equal to *z* (in the sense of\n    <fn["eqv?"](obj1, obj2)>) when converted back to a number by\n    <fn["string->number"](string, radix)>.\n\n    Specified by: <R6RS at\n    http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_580>\n\n    See Also: <fn["string->number"](string, radix)>.\n\n    Function: fn["number->string"](z, radix, precision)\n    Converts and suffixes *z* with a count of significant bits.\n\n    Appends "|p" to each inexact real component of *z* where p is the\n    smallest mantissa width not less than *precision* needed to\n    represent the component exactly.\n\n    Specified by: <R6RS at\n    http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_582>\n\n    Function: fn["string->number"](string)\n    Parses *string* as a Scheme number.  Returns *false* if unable.\n\n    Examples:\n\n    > "1"       - exact 1.\n    > "1."      - inexact 1, same as "1.0".\n    > "1/2"     - exact one-half, same as "2/4" etc.\n    > "0.5"     - inexact 0.5.\n    > "12e3"    - inexact 12000.\n    > "i"       - the imaginary unit.\n    > "-2+1/2i" - exact complex number.\n    > "2.@1"    - complex in polar coordinates, r=2.0, theta=1.0.\n    > "+inf.0"  - positive infinity.\n    > "-inf.0"  - negative infinity.\n    > "+nan.0"  - IEEE NaN (not-a-number).\n    > "#e0.5"   - exact one-half, forced exact by prefix #e.\n    > "#i1/2"   - 0.5, inexact by prefix #i.\n    > "#x22"    - exact 34; prefix #x hexadecimal.\n    > "#o177"   - exact 127; prefix #o octal.\n    > "#b101"   - exact 5; prefix #b binary.\n    > "#i#b101" - inexact 5.0.\n    > "#b#i101" - same.\n    > "1.2345678|24" - rounded as if to single-precision (about 1.23456776).\n\n    Specified by: <R6RS at\n    http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_584>\n\n    See Also: <fn["number->string"](z)>, <R6RS section 4.2.8: Lexical\n    syntax: Numbers at\n    http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-7.html#node_sec_4.2.8>\n\n    Function: fn["string->number"](string, radix)\n    Parses *string* as a Scheme number using *radix* as default radix.\n\n    *radix* must be exact 2, 8, 10, or 16.  If *string* contains a\n    radix prefix, the prefix takes precedence over *radix*.\n\n    Specified by: <R6RS at\n    http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_586>\n\n    See Also: <fn["number->string"](z, radix)>.\n*/\nfunction implementRnrsBase(plugins) {\n    //"use strict";  // Strict mode hinders error reporting.\n    var g = plugins.get("es5globals");\n    var uncurry = plugins.get("uncurry");\n    var SchemeNumber, stringToNumber, ZERO, ONE, MINUS_ONE, INEXACT_ZERO, NAN, raise, isNumber, assertReal, toReal, toRational, toInteger, assertExact, makeRectangular, makePolar;\n    var numberToString, isExact, isInexact, isComplex, isReal, isRational, isInteger, isZero, toExact, toInexact, negate, reciprocal, eq, ne, add, subtract, multiply, divide, realPart, imagPart, expt, exp, magnitude, angle, sqrt, log, asin, acos, atan, sin, cos, tan, SN_isFinite, SN_isInfinite, SN_isNaN, abs, isPositive, isNegative, floor, ceiling, truncate, round, compare, gt, lt, ge, le, divAndMod, div, mod, atan2, numerator, denominator, isEven, isOdd, exactIntegerSqrt, gcdNonnegative;\n    var Array_push = uncurry(g.Array.prototype.push);\n\n    SchemeNumber             = plugins.get("SchemeNumber");\n    numberToString           = plugins.get("numberToString");\n    isExact                  = plugins.get("isExact");\n    isInexact                = plugins.get("isInexact");\n    isComplex                = plugins.get("isComplex");\n    isReal                   = plugins.get("isReal");\n    isRational               = plugins.get("isRational");\n    isInteger                = plugins.get("isInteger");\n    isZero                   = plugins.get("isZero");\n    toExact                  = plugins.get("toExact");\n    toInexact                = plugins.get("toInexact");\n    negate                   = plugins.get("negate");\n    reciprocal               = plugins.get("reciprocal");\n    eq                       = plugins.get("eq");\n    ne                       = plugins.get("ne");\n    add                      = plugins.get("add");\n    subtract                 = plugins.get("subtract");\n    multiply                 = plugins.get("multiply");\n    divide                   = plugins.get("divide");\n    realPart                 = plugins.get("realPart");\n    imagPart                 = plugins.get("imagPart");\n    expt                     = plugins.get("expt");\n    exp                      = plugins.get("exp");\n    magnitude                = plugins.get("magnitude");\n    angle                    = plugins.get("angle");\n    sqrt                     = plugins.get("sqrt");\n    log                      = plugins.get("log");\n    asin                     = plugins.get("asin");\n    acos                     = plugins.get("acos");\n    atan                     = plugins.get("atan");\n    sin                      = plugins.get("sin");\n    cos                      = plugins.get("cos");\n    tan                      = plugins.get("tan");\n    SN_isFinite              = plugins.get("SN_isFinite");\n    SN_isInfinite            = plugins.get("SN_isInfinite");\n    SN_isNaN                 = plugins.get("SN_isNaN");\n    abs                      = plugins.get("abs");\n    isPositive               = plugins.get("isPositive");\n    isNegative               = plugins.get("isNegative");\n    floor                    = plugins.get("floor");\n    ceiling                  = plugins.get("ceiling");\n    truncate                 = plugins.get("truncate");\n    round                    = plugins.get("round");\n    compare                  = plugins.get("compare");\n    gt                       = plugins.get("gt");\n    lt                       = plugins.get("lt");\n    ge                       = plugins.get("ge");\n    le                       = plugins.get("le");\n    divAndMod                = plugins.get("divAndMod");\n    div                      = plugins.get("div");\n    mod                      = plugins.get("mod");\n    atan2                    = plugins.get("atan2");\n    numerator                = plugins.get("numerator");\n    denominator              = plugins.get("denominator");\n    isEven                   = plugins.get("isEven");\n    isOdd                    = plugins.get("isOdd");\n    exactIntegerSqrt         = plugins.get("exactIntegerSqrt");\n    gcdNonnegative           = plugins.get("gcdNonnegative");\n    stringToNumber           = plugins.get("stringToNumber");\n\n    function onPluginsChanged(plugins) {\n        ZERO                     = plugins.get("ZERO");\n        ONE                      = plugins.get("ONE");\n        MINUS_ONE                = plugins.get("MINUS_ONE");\n        INEXACT_ZERO             = plugins.get("INEXACT_ZERO");\n        NAN                      = plugins.get("NAN");\n        raise                    = plugins.get("raise");\n        isNumber                 = plugins.get("isNumber");\n        assertReal               = plugins.get("assertReal");\n        toReal                   = plugins.get("toReal");\n        toRational               = plugins.get("toRational");\n        toInteger                = plugins.get("toInteger");\n        assertExact              = plugins.get("assertExact");\n        makeRectangular          = plugins.get("makeRectangular");\n        makePolar                = plugins.get("makePolar");\n    }\n    plugins.onChange.subscribe(onPluginsChanged);\n    onPluginsChanged(plugins);\n\n    var fn = {\n\n        "eqv?"      : fn_isEqv,\n        "number?"   : fn_isNumber,\n        "complex?"  : fn_isComplex,\n        "real?"     : fn_isReal,\n        "rational?" : fn_isRational,\n        "integer?"  : fn_isInteger,\n        "real-valued?"     : fn_isRealValued,\n        "rational-valued?" : fn_isRationalValued,\n        "integer-valued?"  : fn_isIntegerValued,\n\n        "exact?"   : makeUnary(SchemeNumber, isExact),\n        "inexact?" : makeUnary(SchemeNumber, isInexact),\n\n        inexact : makeUnary(SchemeNumber, toInexact),\n        exact   : makeUnary(SchemeNumber, toExact),\n\n        "="  : fn_equals,\n        "<"  : makeComparator(lt),\n        ">"  : makeComparator(gt),\n        "<=" : makeComparator(le),\n        ">=" : makeComparator(ge),\n\n        "zero?"     : makeUnary(SchemeNumber, isZero),\n        "positive?" : makeUnary(toReal, isPositive),\n        "negative?" : makeUnary(toReal, isNegative),\n        "odd?"      : makeUnary(toInteger, isOdd),\n        "even?"     : makeUnary(toInteger, isEven),\n        "finite?"   : makeUnary(toReal, SN_isFinite),\n        "infinite?" : makeUnary(toReal, SN_isInfinite),\n        "nan?"      : makeUnary(toReal, SN_isNaN),\n\n        max : makeMaxMin(gt),\n        min : makeMaxMin(lt),\n\n        "+" : function() {\n            var ret = ZERO;\n            var len = arguments.length;\n            var i = 0;\n            while (i < len)\n                ret = add(ret, SchemeNumber(arguments[i++]));\n            return ret;\n        },\n\n        "*" : function() {\n            var ret = ONE;\n            var len = arguments.length;\n            var i = 0;\n            while (i < len)\n                ret = multiply(ret, SchemeNumber(arguments[i++]));\n            return ret;\n        },\n\n        "-" : function(a) {\n            var len = arguments.length;\n\n            switch (len) {\n            case 0: args1plus(arguments);\n            case 1: return negate(SchemeNumber(a));\n            }\n            var ret = SchemeNumber(a);\n            var i = 1;\n            while (i < len)\n                ret = subtract(ret, SchemeNumber(arguments[i++]));\n            return ret;\n        },\n\n        "/" : function(a) {\n            var len = arguments.length;\n\n            switch (len) {\n            case 0: args1plus(arguments);\n            case 1: return reciprocal(SchemeNumber(a));\n            case 2: return divide(SchemeNumber(a), SchemeNumber(arguments[1]));\n            }\n            var product = ONE;\n            var i = 1;\n            while (i < len)\n                product = multiply(product, SchemeNumber(arguments[i++]));\n            return divide(SchemeNumber(a), product);\n        },\n\n        abs             : makeUnary(toReal, abs),\n        "div-and-mod"   : makeDivMod(false, 2),\n        div             : makeDivMod(false, 0),\n        mod             : makeDivMod(false, 1),\n        "div0-and-mod0" : makeDivMod(true, 2),\n        div0            : makeDivMod(true, 0),\n        mod0            : makeDivMod(true, 1),\n\n        gcd : function() {\n            var ret = ZERO;\n            var len = arguments.length;\n            var exact = true;\n            for (var i = 0; i < len; i++) {\n                var arg = toInteger(arguments[i]);\n                exact = exact && isExact(arg);\n                ret = gcdNonnegative(ret, toExact(abs(arg)));\n            }\n            ret = abs(ret);\n            return (exact ? ret : toInexact(ret));\n        },\n\n        lcm : function() {\n            var ret = ONE;\n            var len = arguments.length;\n            var exact = true;\n            for (var i = 0; i < len; i++) {\n                var arg = toInteger(arguments[i]);\n                exact = exact && isExact(arg);\n                arg = toExact(abs(arg));\n                ret = divide(multiply(ret, arg), gcdNonnegative(ret, abs(arg)));\n            }\n            return (exact ? ret : toInexact(ret));\n        },\n\n        numerator   : makeUnary(toRational, numerator),\n        denominator : makeUnary(toRational, denominator),\n        floor       : makeUnary(toReal, floor),\n        ceiling     : makeUnary(toReal, ceiling),\n        truncate    : makeUnary(toReal, truncate),\n        round       : makeUnary(toReal, round),\n        rationalize : rationalize,\n        exp         : makeUnary(SchemeNumber, exp),\n\n        log : function(z, base) {\n            var ret = log(SchemeNumber(z));\n            switch (arguments.length) {\n            case 2: ret = divide(ret, log(SchemeNumber(base)));  // fall through\n            case 1: return ret;\n            default: wrongArgCount("1-2", arguments);\n            }\n        },\n\n        sin  : makeUnary(SchemeNumber, sin),\n        cos  : makeUnary(SchemeNumber, cos),\n        tan  : makeUnary(SchemeNumber, tan),\n        asin : makeUnary(SchemeNumber, asin),\n        acos : makeUnary(SchemeNumber, acos),\n\n        atan : function(y, x) {\n            switch (arguments.length) {\n            case 1: return atan(SchemeNumber(y));\n            case 2: return atan2(toReal(y), toReal(x));\n            default: wrongArgCount("1-2", arguments);\n            }\n        },\n\n        sqrt : makeUnary(SchemeNumber, sqrt),\n        "exact-integer-sqrt" : makeUnary(toInteger, exactIntegerSqrt),\n\n        expt : function(a, b) {\n            arguments.length === 2 || args2(arguments);\n            return expt(SchemeNumber(a), SchemeNumber(b));\n        },\n\n        "make-rectangular" : function(x, y) {\n            arguments.length === 2 || args2(arguments);\n            return makeRectangular(toReal(x), toReal(y));\n        },\n\n        "make-polar" : function(r, theta) {\n            arguments.length === 2 || args2(arguments);\n            return makePolar(toReal(r), toReal(theta));\n        },\n\n        "real-part" : makeUnary(SchemeNumber, realPart),\n        "imag-part" : makeUnary(SchemeNumber, imagPart),\n        magnitude   : makeUnary(SchemeNumber, magnitude),\n        angle       : makeUnary(SchemeNumber, angle),\n\n        "number->string" : function(z, radix, precision) {\n            var r = radix;\n            switch (arguments.length) {\n            case 3:\n                precision = toInteger(precision);\n                assertExact(precision);\n                // fall through\n            case 2:\n                r = assertExact(toInteger(r)).valueOf();\n                if (r !== 10 && r !== 16 && r !== 8 && r !== 2)\n                    raise("&assertion", "invalid radix", radix);\n                // fall through\n            case 1: break;\n            default: wrongArgCount("1-3", arguments);\n            }\n            return numberToString(SchemeNumber(z), r, precision);\n        },\n\n        "string->number" : function(s, radix) {\n            switch (arguments.length) {\n            case 1:\n            case 2: return stringToNumber(String(s), radix);\n            default: wrongArgCount("1-2", arguments);\n            }\n        }\n    };\n\n    // Scheme function helpers.\n\n    function wrongArgCount(expected, a) {\n        var msg = "Function"\n\n        // XXX a.callee throws TypeError in strict code.\n        var called;\n        try {\n            called = a.callee;\n        }\n        catch (e) {}\n        if (called) {\n            for (name in fn) {\n                if (fn[name] === called) {\n                    msg += " \'" + name + "\'";\n                    break;\n                }\n            }\n        }\n        raise("&assertion", msg + " expected " + expected +\n              " argument" + (expected == "1" ? "" : "s") + ", got " + a.length);\n    }\n\n    function args1(a) { a.length === 1 || wrongArgCount(1, a); }\n    function args2(a) { a.length === 2 || wrongArgCount(2, a); }\n\n    function args1plus(a) { a.length > 0 || wrongArgCount("1 or more", a); }\n    function args2plus(a) { a.length > 1 || wrongArgCount("2 or more", a); }\n\n    function fn_isEqv(a, b) {\n        arguments.length === 2 || args2(arguments);\n        if (a === b)\n            return true;\n        if (!isNumber(a) || !isNumber(b))\n            return false;\n        return (eq(a, b) && isExact(a) === isExact(b));\n    }\n\n    function fn_isNumber(x) {\n        arguments.length === 1 || args1(arguments);\n        return isNumber(x);\n    }\n\n    function fn_isComplex(x) {\n        arguments.length === 1 || args1(arguments);\n        return isNumber(x) && isComplex(x);\n    }\n\n    function fn_isReal(x) {\n        arguments.length === 1 || args1(arguments);\n        return isNumber(x) && isReal(x);\n    }\n\n    function fn_isRational(x) {\n        arguments.length === 1 || args1(arguments);\n        return isNumber(x) && isRational(x);\n    }\n\n    function fn_isInteger(x) {\n        arguments.length === 1 || args1(arguments);\n        return isNumber(x) && isInteger(x);\n    }\n\n    function fn_isRealValued(x) {\n        arguments.length === 1 || args1(arguments);\n        return isNumber(x) && isComplex(x) && isZero(imagPart(x));\n    }\n\n    function fn_isRationalValued(x) {\n        arguments.length === 1 || args1(arguments);\n        return fn_isRealValued(x) && isRational(realPart(x));\n    }\n\n    function fn_isIntegerValued(x) {\n        arguments.length === 1 || args1(arguments);\n        return fn_isRealValued(x) && isInteger(realPart(x));\n    }\n\n    function fn_equals(a, b) {\n        var len = arguments.length;\n        len > 1 || args2plus(arguments);\n        a = SchemeNumber(a);\n        for (var i = 1; i < len; i++) {\n            if (!eq(a, SchemeNumber(arguments[i])))\n                return false;\n        }\n        return true;\n    }\n\n    function makeUnary(conv, func) {\n        function unary(a) {\n            arguments.length === 1 || args1(arguments);\n            return func(conv(a));\n        }\n        return unary;\n    }\n\n    function makeComparator(cmp) {\n        function comparator(a, b) {\n            var len = arguments.length;\n            len > 1 || args2plus(arguments);\n            b = toReal(b);\n            if (!cmp(toReal(a), b))\n                return false;\n            for (var i = 2; i < len; i++) {\n                var c = toReal(arguments[i]);\n                if (!cmp(b, c))\n                    return false;\n                b = c;\n            }\n            return true;\n        }\n        return comparator;\n    }\n\n    function makeMaxMin(cmp) {\n        function maxMin(a) {\n            var len = arguments.length;\n            len > 0 || args1plus(arguments);\n\n            var ret = toReal(a);\n            var exact = isExact(ret);\n\n            for (var i = 1; i < len; i++) {\n                var x = toReal(arguments[i]);\n                if (SN_isNaN(x))\n                    return x;\n                if (exact) {\n                    exact = isExact(x);\n                    if (!exact)\n                        ret = toInexact(ret);  // XXX Cheaper comparisons?\n                }\n                if (cmp(x, ret) !== false) {\n                    ret = x;\n                }\n            }\n            return exact ? ret : toInexact(ret);\n        }\n        return maxMin;\n    }\n\n    function makeDivMod(is0, which) {\n        function divMod(x, y) {\n            arguments.length === 2 || args2(arguments);\n            x = toReal(x);\n            y = toReal(y);\n\n            if (!SN_isFinite(x))\n                raise("&assertion", "div/mod first argument is not finite", x);\n            if (isZero(y))\n                raise("&assertion", "div/mod second argument is zero", y);\n\n            if (!is0) {\n                switch (which) {\n                case 0: return div(x, y);\n                case 1: return mod(x, y);\n                case 2: default: return divAndMod(x, y);\n                }\n            }\n\n            var dm = divAndMod(x, y);\n            var m = dm[1];\n            var yabs = abs(y);\n\n            if (ge(add(m, m), yabs)) {\n                switch (which) {\n                case 0: return add(dm[0], isNegative(y) ? MINUS_ONE : ONE);\n                case 1: return subtract(m, yabs);\n                case 2: default: return [\n                    add(dm[0], isNegative(y) ? MINUS_ONE : ONE),\n                    subtract(m, yabs)];\n                }\n            }\n            switch (which) {\n            case 0: return dm[0];\n            case 1: return m;\n            case 2: default: return dm;\n            }\n        }\n        return divMod;\n    }\n\n    /* Rationalize is not a method, because I consider it broken by design.\n       It should operate on an open, not closed interval. */\n\n    function rationalize(x, delta) {\n        args2(arguments);\n        x = SchemeNumber(x);\n        delta = SchemeNumber(delta);\n\n        // Handle weird cases first.\n        if (!SN_isFinite(x) || !SN_isFinite(delta)) {\n            assertReal(x);\n            assertReal(delta);\n            if (SN_isInfinite(delta))\n                return (SN_isFinite(x) ? INEXACT_ZERO : NAN);\n            if (SN_isNaN(delta))\n                return delta;\n            return x;\n        }\n\n        if (isZero(delta))\n            return x;\n\n        delta = abs(delta);  // It\'s what PLT and Mosh seem to do.\n\n        var inexact = isInexact(x) || isInexact(delta);\n        if (inexact) {\n            // Ensure that our algorithm terminates.\n            // XXX What if x or delta is irrational?\n            x = toExact(x);\n            delta = toExact(delta);\n        }\n\n        var x0 = subtract(x, delta);\n        var x1 = add(x, delta);\n        var a = floor(x0);\n        var b = floor(x1);\n\n        if (ne(a, b)) {\n            var negative = isNegative(a);\n            if (isNegative(b) != negative)\n                return (inexact ? INEXACT_ZERO : ZERO);\n            a = (negative ? b : ceiling(x0));\n            return inexact ? toInexact(a) : a;\n        }\n        var cf = [];  // Continued fraction, b implied.\n\n        while (true) {\n            x0 = subtract(x0, a);\n            if (isZero(x0))\n                break;\n            x1 = subtract(x1, a);\n            if (isZero(x1))\n                break;\n\n            x0 = reciprocal(x0);\n            x1 = reciprocal(x1);\n            a = floor(x0);\n\n            switch (compare(a, floor(x1))) {\n            case -1: Array_push(cf, ceiling(x0)); break;\n            case  1: Array_push(cf, ceiling(x1)); break;\n            case 0: default:\n                Array_push(cf, a);\n                continue;\n            }\n            break;\n        }\n        var ret = ZERO;\n        var i = cf.length;\n        while (i--)\n            ret = reciprocal(add(ret, cf[i]));\n\n        ret = add(ret, b);\n        return (inexact ? toInexact(ret) : ret);\n    }\n\n    // XXX Should avoid using an object literal in the definition of\n    // *fn* so we don\'t have to worry about inheriting junk from\n    // Object.prototype.\n\n    var api = g.Object.create(null);\n    for (var i in fn) {\n        if (g.Object.prototype.hasOwnProperty.call(fn, i))\n            api[i] = fn[i];\n    }\n\n    return api;\n}\n\n/*\n    Function: implementSchemeNumber(plugins)\n    Creates and returns as *SchemeNumber* a partially constructed\n    <SchemeNumber> object.\n\n    Input:\n\n    *plugins* shall be a <PluginContainer> containing the following\n    elements.  All except *defaultRaise* may be defined after the call\n    to <implementSchemeNumber> but before the first call to its\n    result.\n\n    defaultRaise - the initial value of <SchemeNumber.raise>.\n\n    SchemeNumberType - base constructor of the numerical tower.\n    <SchemeNumber> uses *instanceof SchemeNumberType* to determine\n    whether to return its argument unchanged.\n\n    nativeToInexact - function(number) -> SchemeNumber\n    *number* is a native number.  <nativeToInexact> must return an inexact\n    Scheme Number approximating its argument.  <nativeToInexact> must\n    handle infinite values and *NaN*.\n\n    stringToNumber - function(string) -> SchemeNumber | false\n    *string* is a string.  <stringToNumber> must behave like Scheme\'s\n    *string->number* function given a single argument.  See\n    <fn["string->number"](string)>.\n\n    raise - function(conditionType, message, irritants...)\n    This *raise* simply calls the user-overridable\n    <SchemeNumber.raise> but enforces the contract not to return.\n\n    toSchemeNumber - function(obj) -> SchemeNumber\n    Called when the argument to <SchemeNumber> is not of known\n    convertible type.  The version defined in <defineGenericFunctions>\n    has no imlementations; it exists for applications that want\n    <SchemeNumber> to convert objects other than strings and numbers.\n\n    Returns:\n\n        A new function object like the public <SchemeNumber>.\n*/\nfunction implementSchemeNumber(plugins) {\n    "use strict";\n    var SchemeNumberType, nativeToInexact, stringToNumber, toSchemeNumber, raise;\n\n    function SchemeNumber(obj) {\n        var ret;\n\n        if (obj instanceof SchemeNumberType)\n            return obj;\n\n        if (typeof obj === "string") {\n            ret = stringToNumber(obj);\n            if (ret === false)\n                raise("&assertion", "not a number", obj);\n            return ret;\n        }\n\n        if (typeof obj === "number")\n            return nativeToInexact(obj);\n\n        try {\n            return toSchemeNumber(obj);\n        } catch (e) {\n            raise("&assertion", "not a number", obj,e);\n        }\n    }\n\n    /*\n    Property: VERSION\n    Library version as an array of integers.\n\n    For example, *[1,2,4]* corresponds to Version 1.2.4.\n    */\n    SchemeNumber.VERSION = [1,3,2];\n\n    /*\n    Property: fn\n    Container of <Scheme functions>.\n\n    The <SchemeNumber> object contains a property, <SchemeNumber.fn>,\n    which in turn contains the functions implementing the Scheme\n    numeric types.\n\n    These functions are stored in <fn> under their Scheme names, so\n    ["quotation"] is needed where the names contain characters that\n    are incompatible with dot.notation.  (In JavaScript, *X.Y* and\n    *X["Y"]* are equivalent expressions where Y is a valid identifier.\n    Not all Scheme function names are valid JavaScript identifiers, so\n    one needs the second syntax to extract them from <fn>.)\n\n    You may find it convenient to copy <SchemeNumber>, <fn>, and the\n    output function <number->string> into short-named variables, by\n    convention *sn*, *fn*, and *ns*.  The rest of this section assumes\n    you have done this:\n\n    > var sn = SchemeNumber;\n    > var fn = sn.fn;\n    > var ns = fn["number->string"];\n\n    Functions that require a Scheme number argument automatically\n    filter the argument through <SchemeNumber>.\n\n    For example, *"2"* (string) would be exact (parsed as Scheme) but\n    *2* (equal to *2.0*) would be inexact, as demonstrated:\n\n    > a1 = fn["exact?"]("2");       // a1 === true\n    > a1 = fn["exact?"](sn("2"));   // same\n    > \n    > a2 = fn["exact?"](2);         // a2 === false\n    > a2 = fn["exact?"]("2.0");     // same\n    > a2 = fn["exact?"](sn("2.0")); // same\n\n    Note that the following functions accept arguments of any type and\n    therefore do not apply <SchemeNumber> to their arguments:\n\n    - <eqv?>\n    - <number?>\n    - <complex?>\n    - <real?>\n    - <rational?>\n    - <integer?>\n    - <real-valued?>\n    - <rational-valued?>\n    - <integer-valued?>\n\n    Here, for example, is 2 to the 1,024th power, as a decimal\n    string:\n\n    > a3 = ns(fn.expt("2", "1024"));\n\n    Fractional\n    arithmetic:\n\n    > a4 = fn["+"]("1/3", "4/5");  // 17/15\n\n    Numerator and denominator of a floating-point value,\n    hexadecimal:\n\n    > a5 = ns(fn.numerator(1/3), "16");    // "#i15555555555555"\n    > a6 = ns(fn.denominator(1/3), "16");  // "#i40000000000000"\n\n    The *#i* prefix denotes an inexact number, as detailed in <R6RS at\n    http://www.r6rs.org/>.  Since 1/3 is a native JavaScript number,\n    the library regards it as inexact, and operations such as\n    numerator yield inexact integer results.  If we used *"1/3"*\n    (quoted) instead of *1/3*, the numerator and denominator would be\n    the mathematically correct 1 and 3.\n\n    Functions specified to return two values (such as <div-and-mod>\n    and <exact-integer-sqrt>) return a two-element array as per\n    JavaScript conventions.\n\n    Caveats:\n\n      o Arcane features such as explicit mantissa widths or complex\n        transcendental functions, while believed complete, are\n        unoptimized.\n\n      o The library exhibits other visible behaviors besides those\n        described herein.  However, they are not part of its public\n        API and may change or disappear from one release to the next.\n\n      o In particular, Scheme numbers\' *toString* property sometimes\n        produces output that is incorrect in the Scheme sense.  (This\n        stems from the decision to represent inexact reals as\n        unadorned native numbers.)\n\n    To serialize numbers as Scheme would, use\n    <SchemeNumber.fn["number->string"]>.\n\n    > "" + SchemeNumber(2);                  // "2"\n    > SchemeNumber.fn["number->string"](2);  // "2."\n\n    To test a Scheme number for numerical equality with another Scheme\n    number or a native value, use <fn["="]>.  Likewise for <fn[">"]>\n    etc.\n\n    See Also:\n\n        <Scheme functions>\n    */\n    SchemeNumber.fn = undefined;  // implementRnrsBase(plugins);\n\n    /*\n    Property: raise\n    Function that translates a Scheme exception to ECMAScript.\n\n    When a library function encounters a situation where the Scheme\n    specification requires it to raise an exception with a certain\n    condition type, the function calls <SchemeNumber.raise>.\n\n    Programs may assign a custom function to <SchemeNumber.raise> to\n    intercept such exceptions.\n\n    Parameters:\n\n        conditionType - The specified condition, for example, "&assertion".\n        message       - A string describing the error.\n        irritants...  - Zero or more erroneous data arguments.\n\n    Returns:\n\n        The default <SchemeNumber.raise> function simply throws an\n        *Error*.\n\n    See Also:\n\n        <fn>, <SchemeNumber>\n    */\n    SchemeNumber.raise = undefined;  // plugins.get("defaultRaise");\n\n    /*\n    Property: maxIntegerDigits\n    Maximum size of integers created by the <fn.expt(z1, z2)>\n    function.\n\n    To avoid using up all system memory, exact results of a call to\n    <fn.expt(z1, z2)> are capped at a configurable number of digits,\n    by default one million.  <SchemeNumber.maxIntegerDigits> holds\n    this limit.\n\n    The size limit does *not* currently protect against other means of\n    creating large exact integers.  For example, when passed\n    "#e1e9999999", the <SchemeNumber> function tries to allocate 10\n    million digits, regardless of <maxIntegerDigits>.\n\n    In a future release, cases such as the preceeding example may be\n    checked.  If there is any possibility of legitimately creating\n    such large integers, either as number objects or components\n    thereof, code should increase <maxIntegerDigits>.\n\n    Default Value:\n\n        - 1000000 (1e6 or 1 million)\n    */\n    SchemeNumber.maxIntegerDigits = 1e6;  // 1 million digits.\n\n    /*\n    Property: plugins\n    An instance of <PluginContainer> shared among back-end number\n    implementations in a SchemeNumber system.\n\n    See Also: <defineDebugFunction>\n    */\n    SchemeNumber.plugins = plugins;\n\n    function onPluginsChanged(plugins) {\n        SchemeNumberType = plugins.get("SchemeNumberType");\n        nativeToInexact  = plugins.get("nativeToInexact");\n        stringToNumber   = plugins.get("stringToNumber");\n        toSchemeNumber   = plugins.get("toSchemeNumber");\n        raise            = plugins.get("raise");\n    }\n    plugins.onChange.subscribe(onPluginsChanged);\n    onPluginsChanged(plugins);\n\n    /*\n        SchemeNumber             = plugins.get("SchemeNumber");\n    */\n    return SchemeNumber;\n}\n\nfunction makeMinimalBase() {\n\n    var SchemeNumber, debug;\n\n    var disp = DispatchJs.makeContext({\n        //debug: true,\n        methodNamePrefix: "SN_",\n        methodNameSeparator: " "\n    });\n\n    var plugins = new PluginContainer({\n        Dispatch: disp,\n        es5globals: getEs5Globals()\n    });\n\n    plugins.extend(implementUncurry(plugins));\n    plugins.extend(defineGenericFunctions(plugins));\n    plugins.extend(defineSchemeNumberType(plugins));\n    plugins.extend(defineDebugFunction(plugins));\n\n    // XXX These next steps could be conflated.\n    SchemeNumber = implementSchemeNumber(plugins);\n    plugins.extend("SchemeNumber", SchemeNumber);\n    plugins.extend(implementCoreLibrary(plugins));\n    SchemeNumber.raise = plugins.get("defaultRaise");\n    SchemeNumber.fn = implementRnrsBase(plugins);\n\n    return SchemeNumber;\n}\n\n/*\n    Function: defineAbstractTypes(plugins)\n    Creates a prototype-based type hierarchy corresponding to some of\n    the number classes defined by Scheme.\n\n    The constructors created here ignore their arguments and lack any\n    property other than *prototype* and a few inherited methods noted\n    below.  They may be used as "abstract base classes" to create\n    prototypes of other, more concrete numeric subtypes.\n\n    The hierarchy inherits from the global Number class so that *n\n    instanceof Number* holds for any Scheme number *n*.  The intent is\n    that Scheme numbers should interoperate with native numbers to the\n    extent possible and support the ECMAScript formatting methods\n    *toFixed*, *toExponential*, and *toPrecision*.\n\n    Input:\n\n    *plugins* shall be a <PluginContainer> with the following\n    contents.\n\n    SchemeNumberType - base of the numerical tower\n    Inherits from the built-in *Number* prototype.  Comprises all\n    Scheme numbers.\n\n    Output:\n\n    <defineAbstractTypes> returns an object with the following\n    properties, each a constructor of zero arguments having no side\n    effects.\n\n    Complex - complex number type\n    Inherits from *SchemeNumberType*.\n\n    Real - real number type\n    Inherits from *Complex*.\n\n    InexactReal - inexact real number type\n    Inherits from *Real*.\n\n    ExactReal - exact real number type\n    Inherits from *Real*.\n\n    ExactRational - exact rational number type\n    Inherits from *ExactReal*.\n\n    ExactInteger - exact integer type\n    Inherits from *ExactRational*.\n\n    See Also: <JsDispatch>\n\n    Method: toString()\n    Converts this Scheme number to a string as if by *this.toString(10)*.\n\n    Specified by: <ECMA-262, 5th edition at http://www.ecma-international.org/publications/standards/Ecma-262.htm>\n\n    Method: toString(radix)\n    Converts this Scheme number to a string.\n\n    The *toString* method converts inexact numbers as in JavaScript\n    and exact numbers as if by <fn["number->string"](z, radix)>.\n\n    Method: toFixed(fractionDigits)\n    Returns this Scheme number as a string with *fractionDigits*\n    digits after the decimal point.\n\n    Examples:\n\n    > SchemeNumber("#e1.2").toFixed(2)  // "1.20"\n    > SchemeNumber("2/3").toFixed(20)   // "0.66666666666666666667"\n\n    Compare the native version:\n\n    > (2/3).toFixed(20)                 // "0.66666666666666662966"\n\n    Specified by: <ECMA-262, 5th edition at http://www.ecma-international.org/publications/standards/Ecma-262.htm>\n\n    Method: toLocaleString()\n    Converts this Scheme number to a string as if by *this.toString()*.\n\n    Specified by: <ECMA-262, 5th edition at http://www.ecma-international.org/publications/standards/Ecma-262.htm>\n\n    Method: toExponential(fractionDigits)\n    Converts this Scheme number to scientific "e" notation with\n    *fractionDigits* digits after the decimal point.\n\n    Examples:\n\n    > SchemeNumber("1/11").toExponential(3)  // "9.091e-2"\n    > SchemeNumber("1/2").toExponential(2)   // "5.00e-1"\n\n    Specified by: <ECMA-262, 5th edition at http://www.ecma-international.org/publications/standards/Ecma-262.htm>\n\n    Method: toPrecision(precision)\n    Converts this Scheme number to decimal (possibly "e" notation)\n    with *precision* significant digits.\n\n    Examples:\n\n    > SchemeNumber("12300").toPrecision(2)  // "1.2e+4"\n    > SchemeNumber("12300").toPrecision(4)  // "1.230e+4"\n    > SchemeNumber("12300").toPrecision(5)  // "12300"\n    > SchemeNumber("12300").toPrecision(6)  // "12300.0"\n\n    Specified by: <ECMA-262, 5th edition at http://www.ecma-international.org/publications/standards/Ecma-262.htm>\n\n    Method: valueOf()\n    Converts this Scheme number to a native number with possible loss\n    of precision.\n\n    ECMAScript does not natively support imaginary numbers, so\n    non-reals typically produce *NaN*.\n\n    Specified by: <ECMA-262, 5th edition at http://www.ecma-international.org/publications/standards/Ecma-262.htm>\n */\nfunction defineAbstractTypes(plugins) {\n    "use strict";\n    var g = plugins.get("es5globals");\n    var api = g.Object.create(null);\n    var SchemeNumberType = plugins.get("SchemeNumberType");\n\n    function Complex(){}             Complex.prototype = new SchemeNumberType();\n    function Real(){}                   Real.prototype = new Complex();\n    function InexactReal(){}     InexactReal.prototype = new Real();\n    function ExactReal(){}         ExactReal.prototype = new Real();\n    function ExactRational(){} ExactRational.prototype = new ExactReal();\n    function ExactInteger(){}   ExactInteger.prototype = new ExactRational();\n\n    api.Complex                  = Complex;\n    api.Real                     = Real;\n    api.InexactReal              = InexactReal;\n    api.ExactReal                = ExactReal;\n    api.ExactRational            = ExactRational;\n    api.ExactInteger             = ExactInteger;\n    return api;\n}\n\n/*\n    Function: installAbstractTypes(plugins)\n    Defines dispatcher classes for the results of\n    <defineAbstractTypes(plugins)>.\n\n    *plugins* shall be a <PluginContainer> with the following\n    contents.\n\n    Dispatch - a <JsDispatch> object.\n    <installAbstractTypes> calls the *Dispatch* object\'s *defClass*\n    function to register the new types.  The class names used in\n    *Dispatch* are the same as those used in *plugins*, e.g.,\n    "Complex", except that *SchemeNumberType* is registered as simply\n    "SchemeNumber".\n*/\nfunction installAbstractTypes(plugins) {\n    "use strict";\n    var disp = plugins.get("Dispatch");\n\n    function def(name) {\n        disp.defClass(name, { ctor: plugins.get(name) });\n    }\n    def("Complex");\n    def("Real");\n    def("InexactReal");\n    def("ExactReal");\n    def("ExactRational");\n    def("ExactInteger");\n}\n\nfunction installStubFunctions(plugins) {\n    "use strict";\n    var g = plugins.get("es5globals");\n    var uncurry = plugins.get("uncurry");\n    var Function_apply = uncurry(g.Function.prototype.apply);\n    var Array_concat   = uncurry(g.Array.prototype.concat);\n\n    var SchemeNumberType         = plugins.get("SchemeNumberType");\n    var Complex                  = plugins.get("Complex");\n    var Real                     = plugins.get("Real");\n    var InexactReal              = plugins.get("InexactReal");\n    var ExactReal                = plugins.get("ExactReal");\n    var ExactRational            = plugins.get("ExactRational");\n    var ExactInteger             = plugins.get("ExactInteger");\n\n    function def(name, types) {\n        var func = plugins.get(name);\n        if (!func) {\n            console.log(name, "not found");\n            return;\n        }\n        Function_apply(func.def, func, types /*Array_concat(types, g.undefined)*/);\n    }\n\n    // These are the functions that number implementations must implement.\n    // Example:\n    // var disp = SchemeNumber.plugins.get("Dispatch");\n    // disp.defClass("MyComplex", {ctor: MyComplexConstructor,\n    //                             base: Complex});\n    // var add = SchemeNumber.plugins.get("add");\n    // add.def("MyComplex", Complex, add_MyComplex_to_AnyComplex);\n    // add.def(Complex, "MyComplex", add_AnyComplex_to_MyComplex);\n\n    def("numberToString", [SchemeNumberType]);\n    def("isExact",        [SchemeNumberType]);\n    def("isInexact",      [SchemeNumberType]);\n\n    def("isComplex",      [SchemeNumberType]);\n    def("isReal",         [SchemeNumberType]);\n    def("isRational",     [SchemeNumberType]);\n    def("isInteger",      [SchemeNumberType]);\n    def("isZero",         [SchemeNumberType]);\n\n    def("toExact",        [SchemeNumberType]);\n    def("toInexact",      [SchemeNumberType]);\n    def("negate",         [SchemeNumberType]);\n    def("reciprocal",     [SchemeNumberType]);\n\n    def("eq",             [SchemeNumberType, SchemeNumberType]);\n    def("ne",             [SchemeNumberType, SchemeNumberType]);\n\n    def("add",            [SchemeNumberType, SchemeNumberType]);\n    def("subtract",       [SchemeNumberType, SchemeNumberType]);\n    def("multiply",       [SchemeNumberType, SchemeNumberType]);\n    def("divide",         [SchemeNumberType, SchemeNumberType]);\n\n    def("square",         [SchemeNumberType]);\n\n    def("realPart",       [Complex]);\n    def("imagPart",       [Complex]);\n    def("magnitude",      [Complex]);\n    def("angle",          [Complex]);\n    def("conjugate",      [Complex]);\n\n    def("expt",           [SchemeNumberType, ExactInteger]);\n    def("expt",           [Complex, Complex]);\n\n    def("exp",            [Complex]);\n    def("sqrt",           [Complex]);\n\n    def("log",            [Complex]);\n    def("asin",           [Complex]);\n    def("acos",           [Complex]);\n    def("atan",           [Complex]);\n\n    def("sin",            [Complex]);\n    def("cos",            [Complex]);\n    def("tan",            [Complex]);\n\n    def("SN_isFinite",    [Real]);\n    def("SN_isInfinite",  [Real]);\n    def("SN_isNaN",       [Real]);\n\n    def("isUnit",         [Real]);\n    def("abs",            [Real]);\n    def("isPositive",     [Real]);\n    def("isNegative",     [Real]);\n    def("sign",           [Real]);\n    def("floor",          [Real]);\n    def("ceiling",        [Real]);\n    def("truncate",       [Real]);\n    def("round",          [Real]);\n\n    def("compare",        [Real, Real]);\n    def("gt",             [Real, Real]);\n    def("lt",             [Real, Real]);\n    def("ge",             [Real, Real]);\n    def("le",             [Real, Real]);\n    def("divAndMod",      [Real, Real]);\n    def("div",            [Real, Real]);\n    def("mod",            [Real, Real]);\n    def("atan2",          [Real, Real]);\n\n    def("numerator",      [ExactRational]);\n    def("denominator",    [ExactRational]);\n    def("numeratorAndDenominator", [ExactRational]);\n\n    def("isEven",         [ExactInteger]);\n    def("isOdd",          [ExactInteger]);\n    def("exactIntegerSqrt", [ExactInteger]);\n    def("exp10",          [ExactInteger]);\n    def("gcdNonnegative", [ExactInteger, ExactInteger]);\n    def("divideReduced",  [ExactInteger, ExactInteger]);\n\n    def("bitwiseNot", [ExactInteger]);\n    def("bitwiseAnd", [ExactInteger, ExactInteger]);\n    def("bitwiseIor", [ExactInteger, ExactInteger]);\n    def("bitwiseXor", [ExactInteger, ExactInteger]);\n    def("bitCount", [ExactInteger]);\n    def("bitLength", [ExactInteger]);\n    def("firstBitSet", [ExactInteger]);\n    def("isBitSet", [ExactInteger]);\n    def("copyBit", [ExactInteger]);\n    def("bitField", [ExactInteger]);\n    def("copyBitField", [ExactInteger, ExactInteger]);\n    def("bitShift", [ExactInteger]);\n    def("rotateBitField", [ExactInteger]);\n    def("reverseBitField", [ExactInteger]);\n}\n\n\n/*\n    Function: implementPluginLibrary(plugins)\n    Creates some plugins of use to number implementations.\n\n    Input:\n\n    *plugins* shall be a <PluginContainer> containing the items listed\n    below, in addition to the output of <defineAbstractTypes> and\n    <defineGenericFunctions>.  All may be added after the call to\n    <implementPluginLibrary> but before any use of its results.  When\n    changes to plugins produce changes in non-function results (such\n    as *ZERO* and *ONE*), the library broadcasts the changes via the\n    <PluginLibrary.onChange> event.\n\n    SchemeNumber - function(any)\n    The <SchemeNumber> object as returned by\n    <implementSchemeNumber(plugins)>.\n\n    nativeToExactInteger - function(integer)\n    *integer* is a native ECMAScript number of integer value.\n    <nativeToExactInteger> returns an exact Scheme number whose value\n    equals *integer*.\n\n    nativeToInexact - function(number)\n    *number* is a native ECMAScript number, possibly infinite or\n    *NaN*.  <nativeToInexact> returns an inexact Scheme number\n    approximating its argument.\n\n    parseExactInteger - function(sign, string, radix)\n    *sign* is the native number 1 or -1.  *radix* is the native number\n    2, 8, 10, or 16.  <parseExactInteger> must be a function returning\n    a Scheme number equal to *sign* times the result of parsing\n    *string* as a positive, unprefixed, exact integer in the given\n    radix.\n\n    parseInexact - function(sign, string)\n    *sign* is the native number 1 or -1.  <parseExact> must be a\n    function returning a Scheme number equal to *sign* times the\n    result of parsing *string* as a positive, unprefixed, decimal,\n    inexact, real number.\n\n    exactRectangular - function(x, y)\n    *x* and *y* are exact reals, *y* non-zero.  <exactRectangular>\n    returns an exact complex equal to *x* + (i * *y*).\n\n    inexactRectangular - function(x, y)\n    *x* and *y* are inexact reals.  <inexactRectangular> returns an\n    inexact complex equal to *x* + (i * *y*).\n\n    exactPolar - function(r, theta)\n    *r* and *theta* are exact reals.  <exactPolar> returns an exact\n    complex equal to *r* * exp(i * *theta*).\n\n    inexactPolar - function(r, theta)\n    *r* and *theta* are inexact reals.  <inexactPolar> returns an\n    inexact complex equal to *r* * exp(i * *theta*).\n\n    Output:\n\n    <implementPluginLibrary> returns an object with the following\n    properties.\n\n    ZERO - the exact integer *0*.\n\n    ONE - the exact integer *1*.\n\n    TWO - the exact integer *2*.\n\n    MINUS_ONE - the exact integer *-1*.\n\n    INEXACT_ZERO - the inexact integer *0.0*.\n\n    INEXACT_ONE - the inexact integer *1.0*.\n\n    PI - the inexact real number pi.\n\n    INFINITY - the inexact real number *+inf.0*.\n\n    MINUS_INFINITY - the inexact real number *-inf.0*.\n\n    NAN - the inexact real number *+nan.0*.\n\n    I - the exact complex unit *i*.\n\n    MINUS_I - the exact complex unit *-i*.\n\n    raise - function(conditionType, message, irritant...)\n    This *raise* simply calls the user-overridable\n    <SchemeNumber.raise> but enforces the contract not to return.\n\n    defaultRaise - function(conditionType, message, irritant...)\n    Throws an Error describing the arguments.\n\n    raiseDivisionByExactZero - function()\n    Raises an exception as specified by Scheme to report division by\n    exact zero.\n\n    isNumber - function(x)\n    Returns true if *x* is a Scheme number.\n\n    assertReal - function(x)\n    Returns *x* if *x* is a real Scheme number, otherwise raises an\n    exception as specified by Scheme for invalid argument type.\n\n    toReal - function(x)\n    Converts *x* to a Scheme number and behaves as if by returning\n    *assertReal(x)*.\n\n    assertInteger - function(x)\n    Returns *x* if *x* is a Scheme integer, otherwise raises an\n    exception as specified by Scheme for invalid argument type.\n\n    toInteger - function(x)\n    Converts *x* to a Scheme number and behaves as if by returning\n    *assertInteger(x)*.\n\n    assertExact - function(x)\n    Returns *x* if *x* is an exact Scheme number, otherwise raises an\n    exception as specified by Scheme for invalid argument type.\n\n    Complex_expt - function(power)\n    Returns the value specified for <fn.expt(z1, z2)> (passing *this*\n    and *power*) for the case where *z1* is zero or the result is\n    permitted to be inexact The result may be non-real, even if both\n    arguments are real and *this* is positive.\n\n    Complex_expt_fn - function(z1, z2)\n    Behaves as if by returning *Complex_expt.call(z1, z2)*.\n\n    Complex_asin - function(z)\n    Returns the value specified for <fn.asin(z)> for complex *z*.  The\n    result may be non-real due to inexactness, even if the argument is\n    real and in the range -1 to 1.\n\n    Complex_asin_fn - function(z1, z2)\n    Behaves as if by returning *Complex_asin(z1, z2)*.\n\n    Complex_acos - function(z)\n    Returns the value specified for <fn.acos(z)> for complex *z*.  The\n    result may be non-real due to inexactness, even if the argument is\n    real and in the range -1 to 1.\n\n    Complex_acos_fn - function(z1, z2)\n    Behaves as if by returning *Complex_acos.call(z1, z2)*.\n\n    Complex_atan - function(z)\n    Returns the value specified for <fn.atan(z)> for complex *z*.  The\n    result may be non-real due to inexactness, even if the argument is\n    real.\n\n    Complex_atan_fn - function(z1, z2)\n    Behaves as if by returning *Complex_atan.call(z1, z2)*.\n\n    Complex_log - function(z)\n    Returns the value specified for <fn.log(z)> for complex *z*.  The\n    result may be non-real due to inexactness, even if the argument is\n    real and positive.\n\n    nativeDenominator - function(x)\n    *x* is a native number.  Returns the denominator of *x* regarded\n    as a binary fraction.\n\n    nativeDenominatorLog2 - function(x)\n    *x* is a native number.  Returns the floor of the base-2\n    log of *nativeDenominator(x)*; i.e., the denominator\'s floating\n    point exponent.\n\n    numberToBinary - function(x)\n    Returns a string of "0" and "1" characters, possibly including a\n    "."  and possibly a leading "-", that in base 2 equals x.\n\n    This works by calling *Number.prototype.toString* with a radix of\n    2.  Specification ECMA-262 Edition 5 (December 2009) does not\n    strongly assert that this works.  As an alternative, should this\n    prove non-portable, *nativeDenominator* could instead do this for\n    finite *x*:\n\n    > for (var d = 1; x !== Math.floor(x); d *= 2) {\n    >     x *= 2;\n    > }\n    > return d;\n\n    zeroes - function(count)\n    Returns a string of *count* zeroes, e.g. "0000".\n\n    XXX documentation incomplete.\n\n    truncateToPrecision\n\n    stringToNumber - function(string, radix, exact)\n    <stringToNumber> returns the Scheme number whose external\n    representation is *string* with added prefixes corresponding to\n    either or both of *radix* and *exact*, if defined.\n\n    *s* should be the external representation of a Scheme number, such\n    as "2/3" or "#e1.1@-2d19".  If *s* does not represent a Scheme\n    number, <stringToNumber> returns *false*.\n\n    If *radix* is given, it must be either 2, 8, 10, or 16, and *s*\n    must not contain a radix prefix.  The function behaves as if *s*\n    did contain the prefix corresponding to *radix*.\n\n    If *exact* is given, it must have type "boolean", and *s* must not\n    contain an exactness prefix.  The function behaves as if *s*\n    contained the corresponding prefix ("#e" if *exact* is true, "#i"\n    if false).\n*/\nfunction implementPluginLibrary(plugins) {\n    "use strict";\n\n    // Abstract types, generic functions, and the SchemeNumber object.\n    // XXX Could remove unused items.\n    var SchemeNumber, toSchemeNumber, SchemeNumberType, Complex, Real,\n        InexactReal, ExactReal, ExactRational, ExactInteger,\n        numberToString, isExact, isInexact, isComplex, isReal,\n        isRational, isInteger, isZero, toExact, toInexact, negate,\n        reciprocal, eq, ne, add, subtract, multiply, divide, square,\n        realPart, imagPart, expt, expt, exp, magnitude, angle, sqrt,\n        log, asin, acos, atan, sin, cos, tan, SN_isFinite,\n        SN_isInfinite, SN_isNaN, isUnit, abs, isPositive, isNegative,\n        sign, floor, ceiling, truncate, round, compare, gt, lt, ge,\n        le, divAndMod, div, mod, atan2, numerator, denominator,\n        numeratorAndDenominator,\n        isEven, isOdd, exp10, gcdNonnegative, divideReduced;\n\n    SchemeNumber             = plugins.get("SchemeNumber");\n\n    SchemeNumberType         = plugins.get("SchemeNumberType");\n    Complex                  = plugins.get("Complex");\n    Real                     = plugins.get("Real");\n    InexactReal              = plugins.get("InexactReal");\n    ExactReal                = plugins.get("ExactReal");\n    ExactRational            = plugins.get("ExactRational");\n    ExactInteger             = plugins.get("ExactInteger");\n\n    toSchemeNumber           = plugins.get("toSchemeNumber");\n    numberToString           = plugins.get("numberToString");\n    isExact                  = plugins.get("isExact");\n    isInexact                = plugins.get("isInexact");\n    isComplex                = plugins.get("isComplex");\n    isReal                   = plugins.get("isReal");\n    isRational               = plugins.get("isRational");\n    isInteger                = plugins.get("isInteger");\n    isZero                   = plugins.get("isZero");\n    toExact                  = plugins.get("toExact");\n    toInexact                = plugins.get("toInexact");\n    negate                   = plugins.get("negate");\n    reciprocal               = plugins.get("reciprocal");\n    eq                       = plugins.get("eq");\n    ne                       = plugins.get("ne");\n    add                      = plugins.get("add");\n    subtract                 = plugins.get("subtract");\n    multiply                 = plugins.get("multiply");\n    divide                   = plugins.get("divide");\n    square                   = plugins.get("square");\n    realPart                 = plugins.get("realPart");\n    imagPart                 = plugins.get("imagPart");\n    expt                     = plugins.get("expt");\n    expt                     = plugins.get("expt");\n    exp                      = plugins.get("exp");\n    magnitude                = plugins.get("magnitude");\n    angle                    = plugins.get("angle");\n    sqrt                     = plugins.get("sqrt");\n    log                      = plugins.get("log");\n    asin                     = plugins.get("asin");\n    acos                     = plugins.get("acos");\n    atan                     = plugins.get("atan");\n    sin                      = plugins.get("sin");\n    cos                      = plugins.get("cos");\n    tan                      = plugins.get("tan");\n    SN_isFinite              = plugins.get("SN_isFinite");\n    SN_isInfinite            = plugins.get("SN_isInfinite");\n    SN_isNaN                 = plugins.get("SN_isNaN");\n    isUnit                   = plugins.get("isUnit");\n    abs                      = plugins.get("abs");\n    isPositive               = plugins.get("isPositive");\n    isNegative               = plugins.get("isNegative");\n    sign                     = plugins.get("sign");\n    floor                    = plugins.get("floor");\n    ceiling                  = plugins.get("ceiling");\n    truncate                 = plugins.get("truncate");\n    round                    = plugins.get("round");\n    compare                  = plugins.get("compare");\n    gt                       = plugins.get("gt");\n    lt                       = plugins.get("lt");\n    ge                       = plugins.get("ge");\n    le                       = plugins.get("le");\n    divAndMod                = plugins.get("divAndMod");\n    div                      = plugins.get("div");\n    mod                      = plugins.get("mod");\n    atan2                    = plugins.get("atan2");\n    numerator                = plugins.get("numerator");\n    denominator              = plugins.get("denominator");\n    numeratorAndDenominator  = plugins.get("numeratorAndDenominator");\n    isEven                   = plugins.get("isEven");\n    isOdd                    = plugins.get("isOdd");\n    exp10                    = plugins.get("exp10");\n    gcdNonnegative           = plugins.get("gcdNonnegative");\n    divideReduced            = plugins.get("divideReduced");\n\n    // Functions to be provided by number implementations.\n    var nativeToExactInteger, divideReducedNotByOne;\n    var exactRectangular, inexactRectangular;\n\n    // Imports from ECMAScript.\n    var g                = plugins.get("es5globals");\n    var uncurry          = plugins.get("uncurry");\n    var Array_join       = uncurry(g.Array.prototype.join);\n    var Number_toString  = uncurry(g.Number.prototype.toString);\n    var String_indexOf   = uncurry(g.String.prototype.indexOf);\n    var String_substring = uncurry(g.String.prototype.substring);\n    var String_replace   = uncurry(g.String.prototype.replace);\n\n    var Math_LN10    = g.Math.LN10;\n    var Math_LN2     = g.Math.LN2;\n    var Math_abs     = g.Math.abs;\n    var Math_floor   = g.Math.floor;\n    var Math_pow     = g.Math.pow;\n    var _undefined   = g.undefined;\n    var _NaN         = g.NaN;\n    var _parseInt    = g.parseInt;\n    var _isFinite    = g.isFinite;\n\n    // Imports from implementations via core library.\n    var ZERO, ONE, TWO, MINUS_ONE, I, MINUS_I, INEXACT_ZERO, INEXACT_ONE, PI;\n\n    // Imports from core library.\n    var makePolar                = plugins.get("makePolar");\n    var makeRectangular          = plugins.get("makeRectangular");\n    var raise                    = plugins.get("raise");\n    var raiseDivisionByExactZero = plugins.get("raiseDivisionByExactZero");\n\n    var api = g.Object.create(null);\n\n    function onPluginsChanged(plugins, changed) {\n        nativeToExactInteger     = plugins.get("nativeToExactInteger");\n        divideReducedNotByOne    = plugins.get("divideReducedNotByOne");\n        exactRectangular         = plugins.get("exactRectangular");\n        inexactRectangular       = plugins.get("inexactRectangular");\n\n        ZERO                     = plugins.get("ZERO");\n        ONE                      = plugins.get("ONE");\n        TWO                      = plugins.get("TWO");\n        MINUS_ONE                = plugins.get("MINUS_ONE");\n        INEXACT_ZERO             = plugins.get("INEXACT_ZERO");\n        INEXACT_ONE              = plugins.get("INEXACT_ONE");\n        PI                       = plugins.get("PI");\n        I                        = plugins.get("I");\n        MINUS_I                  = plugins.get("MINUS_I");\n    }\n    plugins.onChange.subscribe(onPluginsChanged);\n    onPluginsChanged(plugins, {});\n\n    //\n    // For lazy implementors.  Used in Complex and elsewhere.  These\n    // belong in a separate library.  Could support replacement with\n    // dummy versions that return NaN.\n    //\n\n    function Complex_sqrt() {\n        return makePolar(sqrt(magnitude(this)), divide(angle(this), TWO));\n    }\n    function Complex_exp() {\n        return makePolar(exp(realPart(this)), imagPart(this));\n    }\n    function Complex_sin() {\n        var iz = multiply(I, this);\n        return multiply(divide(subtract(exp(iz), exp(negate(iz))), TWO),\n                        MINUS_I);\n    }\n    function Complex_cos() {\n        var iz = multiply(I, this);\n        return divide(add(exp(iz), exp(negate(iz))), TWO);\n    }\n\n    function Complex_expt_fn(b, p) {\n        if (isZero(b)) {\n            if (isZero(p))\n                return isExact(b) && isExact(p) ? ONE : INEXACT_ONE;\n            if (isPositive(realPart(p)))\n                return isExact(p) ? b : INEXACT_ZERO;\n            raise("&implementation-restriction",\n                  "invalid power for zero expt", p);\n        }\n        return exp(multiply(log(b), p));\n    }\n    function Complex_asin_fn(z) {\n        return multiply(MINUS_I,\n                        log(add(multiply(I, z),\n                                sqrt(subtract(ONE, square(z))))));\n    }\n\n    function Complex_acos_fn(z) {\n        return subtract(divide(PI, TWO), Complex_asin_fn(z));\n    }\n\n    function Complex_atan_fn(z) {\n        var iz = multiply(I, z);\n        return multiply(divide(subtract(log(add(ONE, iz)),\n                                        log(subtract(ONE, iz))), TWO),\n                        MINUS_I);\n    }\n\n    function Complex_log_fn(z) {\n        return makeRectangular(log(magnitude(z)), angle(z));\n    }\n\n    function Complex_expt(p) { return Complex_expt_fn(this, p); }\n    function Complex_asin()  { return Complex_asin_fn(this); }\n    function Complex_acos()  { return Complex_acos_fn(this); }\n    function Complex_atan()  { return Complex_atan_fn(this); }\n    function Complex_log()   { return Complex_log_fn( this); }\n\n    function Complex_valueOf() {\n        if (isZero(imagPart(this)))\n            return realPart(this).valueOf();\n        return _NaN;\n    }\n\n    //\n    // For Rectangular.\n    //\n\n    function xyToString(xString, yString) {\n        if (yString[0] === \'-\' || yString[0] === \'+\')\n            return xString + yString + "i";\n        return xString + "+" + yString + "i";\n    }\n\n    function Complex_numberToString(radix, precision) {\n        return xyToString(numberToString(realPart(this), radix, precision),\n                          numberToString(imagPart(this), radix, precision));\n    }\n\n    function Complex_toString(radix) {\n        radix = radix || 10;\n        return xyToString(realPart(this).toString(radix),\n                          imagPart(this).toString(radix));\n    }\n\n    function Complex_toFixed(dig) {\n        return xyToString(realPart(this).toFixed(dig),\n                          imagPart(this).toFixed(dig));\n    }\n    function Complex_toExponential(dig) {\n        return xyToString(realPart(this).toExponential(dig),\n                          imagPart(this).toExponential(dig));\n    }\n    function Complex_toPrecision(prec) {\n        return xyToString(realPart(this).toPrecision(prec),\n                          imagPart(this).toPrecision(prec));\n    }\n\n    function Complex_toInexact() {\n        if (isInexact(this))\n            return this;\n        return inexactRectangular(toInexact(realPart(this)),\n                                  toInexact(imagPart(this)));\n    }\n\n    function Complex_toExact() {\n        if (isExact(this))\n            return this;\n        return exactRectangular(toExact(realPart(this)),\n                                toExact(imagPart(this)));\n    }\n\n    function Complex_isZero() {\n        return isZero(realPart(this)) && isZero(imagPart(this));\n    }\n\n    function Complex_magnitude() {\n        var x = realPart(this), y = imagPart(this);\n        if (isZero(x))\n            return abs(y);\n        if (isZero(y))\n            return abs(x);\n        return sqrt(add(square(x), square(y)));\n    }\n\n    function Complex_angle() {\n        return atan2(imagPart(this), realPart(this));\n    }\n\n    function Complex_eq(z) {\n        return (eq(realPart(this), realPart(z)) &&\n                eq(imagPart(this), imagPart(z)));\n    }\n    function Complex_eq_Real(x) {\n        return isZero(imagPart(this)) && eq(x, realPart(this));\n    }\n    function Real_eq_Complex(z) {\n        return isZero(imagPart(z)) && eq(realPart(z), this);\n    }\n\n    function Complex_ne(z) {\n        return (ne(realPart(this), realPart(z)) ||\n                ne(imagPart(this), imagPart(z)));\n    }\n    function Complex_ne_Real(x) {\n        return !isZero(imagPart(this)) || ne(x, realPart(this));\n    }\n    function Real_ne_Complex(z) {\n        return !isZero(imagPart(z)) || ne(realPart(z), this);\n    }\n\n    function Real_add_Complex(z) {\n        return makeRectangular(add(this, realPart(z)), imagPart(z));\n    }\n    function Complex_add_Real(x) {\n        return makeRectangular(add(realPart(this), x), imagPart(this));\n    }\n    function Complex_add(z) {\n        return makeRectangular(add(realPart(this), realPart(z)),\n                               add(imagPart(this), imagPart(z)));\n    }\n\n    function Real_subtract_Complex(z) {\n        return makeRectangular(subtract(this, realPart(z)),\n                               negate(imagPart(z)));\n    }\n    function Complex_subtract_Real(x) {\n        return makeRectangular(subtract(realPart(this), x), imagPart(this));\n    }\n    function Complex_subtract(z) {\n        return makeRectangular(subtract(realPart(this), realPart(z)),\n                               subtract(imagPart(this), imagPart(z)));\n    }\n\n    function Complex_negate() {\n        return makeRectangular(negate(realPart(this)), negate(imagPart(this)));\n    }\n\n    function complexMultiply(ax, ay, bx, by) {\n        return makeRectangular(subtract(multiply(ax, bx), multiply(ay, by)),\n                               add(     multiply(ax, by), multiply(ay, bx)));\n    }\n\n    function Real_multiply_Complex(z) {\n        return makeRectangular(multiply(realPart(z), this),\n                               multiply(imagPart(z), this));\n    }\n    function Complex_multiply_Real(x) {\n        return makeRectangular(multiply(realPart(this), x),\n                               multiply(imagPart(this), x));\n    }\n    function Complex_multiply(z) {\n        return complexMultiply(realPart(this), imagPart(this), realPart(z),\n                               imagPart(z));\n    }\n\n    function Complex_divide_Real(x) {\n        return makeRectangular(divide(realPart(this), x),\n                               divide(imagPart(this), x));\n    }\n\n    function Complex_square() {\n        var x = realPart(this), y = imagPart(this);\n        var xy = multiply(x, y);\n        return makeRectangular(subtract(square(x), square(y)), add(xy, xy));\n    }\n\n    function Complex_reciprocal() {\n        var x = realPart(this), y = imagPart(this);\n        var m2 = add(square(x), square(y));\n        return makeRectangular(divide(x, m2), negate(divide(y, m2)));\n    }\n\n    function complexDivide(x, y, z) {  // returns (x + iy) / z\n        var zx = realPart(z), zy = imagPart(z);\n        var m2 = add(square(zx), square(zy));\n        return complexMultiply(x, y, divide(zx, m2), negate(divide(zy, m2)));\n    }\n\n    function Real_divide_Complex(z) {\n        return complexDivide(this, isExact(this) ? ZERO : INEXACT_ZERO, z);\n    }\n    function Complex_divide(z) {\n        return complexDivide(realPart(this), imagPart(this), z);\n    }\n\n    //\n    // For flonums.  Could be used by an exact binary rational type.\n    // Useful for anyone who needs to inspect native nums, like\n    // frexp() in C.  Keep in core for now.\n    //\n\n    function numberToBinary(x) {\n        return Number_toString(x, 2);\n    }\n\n    function nativeDenominatorLog2(x) {\n        //assert(typeof x === "number");\n        //assert(SN_isFinite(x));\n        var s = numberToBinary(Math_abs(x));\n        var i = String_indexOf(s, ".");\n        if (i === -1)\n            return 0;\n        return s.length - i - 1;\n    }\n\n    function nativeDenominator(x) {\n        // Get the "denominator" of a floating point value.\n        // The result will be a power of 2.\n        //assert(SN_isFinite(x));\n        return Math_pow(2, nativeDenominatorLog2(x));\n    }\n\n    //\n    // For lazy implementors.  Put in separate library.\n    //\n\n    function square_via_multiply() {\n        return multiply(this, this);\n    }\n    function isInexact_via_isExact() {\n        return !isExact(this);\n    }\n    function ne_via_eq(n) {\n        return !eq(this, n);\n    }\n    function subtract_via_negate_add(n) {\n        return add(this, negate(n));\n    }\n    function divide_via_reciprocal_multiply(n) {\n        return multiply(this, reciprocal(n));\n    }\n\n    function complex_or_exact_expt(n) {\n        if (isExact(this))\n            return expt_N_EI_fn(this, n);\n        return Complex_expt_fn(this, n);\n    }\n    function tan_via_divide_sin_cos() {\n        return divide(sin(this), cos(this));\n    }\n\n    function isUnit_via_eq() {\n        return eq(ONE, this) || eq(MINUS_ONE, this);\n    }\n    function Real_magnitude_via_abs() {\n        return abs(this);\n    }\n    function InexactReal_angle_via_isNegative() {\n        return isNegative(this) ? PI : INEXACT_ZERO;\n    }\n    function ExactReal_angle_via_isNegative() {\n        return isNegative(this) ? PI : ZERO;\n    }\n\n    function isPositive_via_sign() { return sign(this) > 0; }\n    function isNegative_via_sign() { return sign(this) < 0; }\n    function isZero_via_sign()     { return sign(this) === 0; }\n    function sign_via_compare()    { return compare(this, ZERO); }\n\n    function eq_via_compare(x) { return compare(this, x) === 0; };\n    function ne_via_compare(x) { return compare(this, x) !== 0; };\n    function gt_via_compare(x) { return compare(this, x) > 0; };\n    function lt_via_compare(x) { return compare(this, x) < 0; };\n    function ge_via_compare(x) { return compare(this, x) >= 0; };\n    function le_via_compare(x) { return compare(this, x) <= 0; };\n\n    function div_R_R(x, y) {\n        return (isNegative(y) ? ceiling(divide(x, y)) : floor(divide(x, y)));\n    }\n    function divAndMod_via_divide_floor(y) {\n        var div = div_R_R(this, y);\n        return [div, subtract(this, multiply(div, y))];\n    }\n    function div_via_divide_floor(y) {\n        return div_R_R(this, y);\n    }\n    function mod_via_divide_floor(y) {\n        return subtract(this, multiply(div_R_R(this, y), y));\n    }\n\n    function abs_via_isNegative_negate() {\n        return isNegative(this) ? negate(this) : this;\n    }\n\n    function ceiling_via_floor() {\n        return isInteger(this) ? this : add(ONE, floor(this));\n    }\n    function truncate_via_ceiling_floor() {\n        return isNegative(this) ? ceiling(this) : floor(this);\n    }\n    function round_via_floor_compare_isEven() {\n        var ret = floor(this);\n        var diff = subtract(this, ret);\n        var twice = add(diff, diff);\n        switch (compare(twice, ONE)) {\n        case -1: return ret;\n        case  1: return add(ONE, ret);\n        case 0: default: return (isEven(ret) ? ret : add(ONE, ret));\n        }\n    }\n\n    function divideReduced_via_isUnit(d) {\n        //assert(isPositive(this));\n        if (isUnit(d))\n            return this;\n        return divideReducedNotByOne(this, d);\n    }\n\n    function Integer_divide_via_gcd_div(d) {\n        //assert(!isZero(d))\n        //require(\'repl\').start();\n        var n = this;\n        var g = gcdNonnegative(abs(d), abs(n));\n        n = div(n, g);\n        d = div(d, g);\n        if (isNegative(d)) {\n            n = negate(n);\n            d = negate(d);\n        }\n        return (isUnit(d) ? n : divideReducedNotByOne(n, d));\n    }\n\n    function Integer_reciprocal_via_divideReduced() {\n        switch (sign(this)) {\n        case -1: return divideReduced(MINUS_ONE, negate(this));\n        case 1:  return divideReduced(ONE, this);\n        case 0: default: return raiseDivisionByExactZero();\n        }\n    }\n\n    //\n    // Pretty generic exact rational output impl.\n    //\n    // Assumes numerator(this) !== this.\n    function ExactRational_numberToString(radix) {\n        var nd = numeratorAndDenominator(this);\n        var n = nd[0], d = nd[1];\n        if (isUnit(d))\n            return numberToString(n, radix);\n        return (numberToString(n, radix) +\n                "/" + numberToString(d, radix));\n    }\n\n    function Integer_numeratorAndDenominator() {\n        return [this, ONE];\n    }\n\n    //\n    // For lazy implementors.\n    //\n\n    function genericExp10(p) {\n        return multiply(this, expt_N_EI_fn(nativeToExactInteger(10), p));\n    }\n\n    function expt_N_EI_fn(z, p) {\n        // Return z raised to the power of integer p.\n        var bits = abs(p);\n        var squarer = z;\n        var ret = ONE;\n        var dm;\n        while (isPositive(bits)) {\n            dm = divAndMod(bits, TWO);\n            bits = dm[0];\n            if (!isZero(dm[1]))\n                ret = multiply(ret, squarer);\n            squarer = square(squarer);\n        }\n        return (isNegative(p) ? reciprocal(ret) : ret);\n    }\n    function expt_N_EI(p) {\n        return expt_N_EI_fn(this, p);\n    }\n\n    function gcdNonnegative_via_isZero_mod(b) {\n        var a = this;\n        //assert(!isNegative(a));\n        //assert(!isNegative(b));\n        var c;\n        while (!isZero(a)) {\n            c = a;\n            a = mod(b, a);\n            b = c;\n        }\n        return b;\n    }\n\n    function bitwiseNot_via_subtract() {\n        return subtract(MINUS_ONE, this);\n    }\n\n    //\n    // For ECMAScript Number formatting methods.\n    //\n\n    function zeroes(count) {\n        var ret = String_substring("000000000000000", 0, count & 15);\n        if (count > 15) {\n            ret += Array_join(new g.Array((count >> 4) + 1),\n                              "0000000000000000");\n        }\n        return ret;\n    }\n\n    // Specified by ECMA-262, 5th edition, 15.7.4.5.\n    function Real_toFixed(fractionDigits) {\n        var f = (fractionDigits === _undefined ? 0 :\n                 _parseInt(fractionDigits, 10));\n        if (f > SchemeNumber.maxIntegerDigits)\n            throw new RangeError("fractionDigits exceeds " +\n                                 "SchemeNumber.maxIntegerDigits: " +\n                                 fractionDigits);\n\n        var x = this;\n        var s = "";\n        if (isNegative(x)) {\n            x = negate(x);\n            s = "-";\n        }\n\n        var p = exp10(ONE, nativeToExactInteger(-f));\n        var dm = divAndMod(x, p);\n        var n = dm[0];\n        if (ge(add(dm[1], dm[1]), p))\n            n = add(ONE, n);\n        if (isZero(n))\n            return s + "0" +\n                (fractionDigits > 0 ? "." + zeroes(fractionDigits) : "");\n        n = numberToString(n);\n        if (f === 0)\n            return s + n;\n\n        var z = f - n.length;\n        if (f > 0) {\n            if (z >= 0)\n                n = zeroes(z + 1) + n;\n            var point = n.length - f;\n            return s + String_substring(n, 0, point) + "." +\n                String_substring(n, point);\n        }\n        return s + n + zeroes(-f);\n    }\n\n    function Real_toExponential(fractionDigits) {\n        var f = (fractionDigits === _undefined ? 20 :\n                 _parseInt(fractionDigits, 10));\n        if (f < 0)\n            throw new RangeError("SchemeNumber toExponential: negative " +\n                                 "argument: " + f);\n        if (f > SchemeNumber.maxIntegerDigits)\n            throw new RangeError("fractionDigits exceeds " +\n                                 "SchemeNumber.maxIntegerDigits: " +\n                                 fractionDigits);\n\n        var x = this;\n        var s = "";\n        if (isNegative(x)) {\n            x = negate(x);\n            s = "-";\n        }\n        else if (isZero(x))\n            return "0" + (fractionDigits > 0 ? "." + zeroes(f) : "") + "e+0";\n\n        var e = Math_floor(log(x) / Math_LN10);\n        var p = exp10(ONE, nativeToExactInteger(e - f));\n        var dm = divAndMod(x, p);\n        var n = dm[0];\n        if (ge(add(dm[1], dm[1]), p))\n            n = add(ONE, n);\n        n = numberToString(n);\n\n        // Adjust for inaccuracy in log().\n        if (n.length != f + 1) {\n            //console.log("Guessed wrong length: " + n.length + " != " + (f + 1));\n            e += n.length - (f + 1);\n            p = exp10(ONE, nativeToExactInteger(e - f));\n            dm = divAndMod(x, p);\n            n = dm[0];\n            if (ge(add(dm[1], dm[1]), p))\n                n = add(ONE, n);\n            n = numberToString(n);\n            if (n.length != f + 1)\n                // Can not format as exponential.\n                return numberToString(this);\n        }\n\n        if (fractionDigits === _undefined)\n            n = String_replace(n, /(\\d)0+$/, "$1");\n        if (n.length > 1)\n            n = n[0] + "." + String_substring(n, 1);\n        return s + n + "e" + (e < 0 ? "" : "+") + e;\n    }\n\n    function Real_toPrecision(precision) {\n        var p, x;\n        if (precision === _undefined) {\n            x = toInexact(this);\n            if (SN_isFinite(x))\n                return Number_toString(+x);\n            p = 21;\n        }\n        else {\n            p = _parseInt(precision, 10);\n            if (p < 1)\n                throw new RangeError("SchemeNumber toPrecision: expected a " +\n                                     "positive precision, got: " + precision);\n            if (p > SchemeNumber.maxIntegerDigits)\n                throw new RangeError("precision exceeds " +\n                                     "SchemeNumber.maxIntegerDigits: " +\n                                     precision);\n        }\n\n        x = this;\n        var s = "";\n        if (isNegative(x)) {\n            x = negate(x);\n            s = "-";\n        }\n        else if (isZero(x))\n            return "0" + (p > 1 ? "." + zeroes(p - 1) : "");\n\n        var ret = x.toExponential(p - 1);\n        var eIndex = String_indexOf(ret, \'e\');\n        var exponent = _parseInt(String_substring(ret, eIndex + 1), 10);\n        if (exponent >= -6 && exponent < p) {\n            if (exponent === 0)\n                ret = String_substring(ret, 0, eIndex);\n            else {\n                ret = String_substring(ret, 0, 1)\n                    + (String_indexOf(ret, \'.\') === -1 ? "" :\n                       String_substring(ret, 2, eIndex));\n                if (exponent < 0)\n                    ret = "0." + zeroes(-1 - exponent) + ret;\n                else if (exponent < p - 1)\n                    ret = (String_substring(ret, 0, exponent + 1) + "." +\n                           String_substring(ret, exponent + 1));\n            }\n        }\n        else if (precision === _undefined) {\n            ret = String_replace(String_substring(ret, 0, eIndex), /\\.?0+/, "")\n                + String_substring(ret, eIndex);\n        }\n\n        return s + ret;\n    }\n\n    //\n    // End library function definitions.\n    //\n\n    api.Complex_sqrt             = Complex_sqrt;\n    api.Complex_exp              = Complex_exp;\n    api.Complex_sin              = Complex_sin;\n    api.Complex_cos              = Complex_cos;\n    api.Complex_expt_fn          = Complex_expt_fn;\n    api.Complex_expt             = Complex_expt;\n    api.Complex_asin_fn          = Complex_asin_fn;\n    api.Complex_asin             = Complex_asin;\n    api.Complex_acos_fn          = Complex_acos_fn;\n    api.Complex_acos             = Complex_acos;\n    api.Complex_atan_fn          = Complex_atan_fn;\n    api.Complex_atan             = Complex_atan;\n    api.Complex_log_fn           = Complex_log_fn;\n    api.Complex_log              = Complex_log;\n\n    api.Complex_numberToString   = Complex_numberToString;\n    api.Complex_toString         = Complex_toString;\n    api.Complex_toFixed          = Complex_toFixed;\n    api.Complex_toExponential    = Complex_toExponential;\n    api.Complex_toPrecision      = Complex_toPrecision;\n    api.Complex_toInexact        = Complex_toInexact;\n    api.Complex_toExact          = Complex_toExact;\n    api.Complex_isZero           = Complex_isZero;\n    api.Complex_magnitude        = Complex_magnitude;\n    api.Complex_angle            = Complex_angle;\n    api.Complex_eq               = Complex_eq;\n    api.Complex_eq_Real          = Complex_eq_Real;\n    api.Real_eq_Complex          = Real_eq_Complex;\n    api.Complex_ne               = Complex_ne;\n    api.Complex_ne_Real          = Complex_ne_Real;\n    api.Real_ne_Complex          = Real_ne_Complex;\n    api.Real_add_Complex         = Real_add_Complex;\n    api.Complex_add_Real         = Complex_add_Real;\n    api.Complex_add              = Complex_add;\n    api.Real_subtract_Complex    = Real_subtract_Complex;\n    api.Complex_subtract_Real    = Complex_subtract_Real;\n    api.Complex_subtract         = Complex_subtract;\n    api.Complex_negate           = Complex_negate;\n    api.Real_multiply_Complex    = Real_multiply_Complex;\n    api.Complex_multiply_Real    = Complex_multiply_Real;\n    api.Complex_multiply         = Complex_multiply;\n    api.Complex_divide_Real      = Complex_divide_Real;\n    api.Complex_square           = Complex_square;\n    api.Complex_reciprocal       = Complex_reciprocal;\n    api.Real_divide_Complex      = Real_divide_Complex;\n    api.Complex_divide           = Complex_divide;\n\n    api.numberToBinary           = numberToBinary;\n    api.nativeDenominatorLog2    = nativeDenominatorLog2;\n    api.nativeDenominator        = nativeDenominator;\n\n    api.square_via_multiply      = square_via_multiply;\n    api.isInexact_via_isExact    = isInexact_via_isExact;\n    api.ne_via_eq                = ne_via_eq;\n    api.subtract_via_negate_add  = subtract_via_negate_add;\n    api.divide_via_reciprocal_multiply= divide_via_reciprocal_multiply;\n    api.complex_or_exact_expt    = complex_or_exact_expt;\n    api.tan_via_divide_sin_cos   = tan_via_divide_sin_cos;\n    api.isUnit_via_eq            = isUnit_via_eq;\n    api.Real_magnitude_via_abs   = Real_magnitude_via_abs;\n    api.InexactReal_angle_via_isNegative= InexactReal_angle_via_isNegative;\n    api.ExactReal_angle_via_isNegative= ExactReal_angle_via_isNegative;\n    api.isPositive_via_sign      = isPositive_via_sign;\n    api.isNegative_via_sign      = isNegative_via_sign;\n    api.isZero_via_sign          = isZero_via_sign;\n    api.sign_via_compare         = sign_via_compare;\n    api.eq_via_compare           = eq_via_compare;\n    api.ne_via_compare           = ne_via_compare;\n    api.gt_via_compare           = gt_via_compare;\n    api.lt_via_compare           = lt_via_compare;\n    api.ge_via_compare           = ge_via_compare;\n    api.le_via_compare           = le_via_compare;\n    api.divAndMod_via_divide_floor= divAndMod_via_divide_floor;\n    api.div_via_divide_floor     = div_via_divide_floor;\n    api.mod_via_divide_floor     = mod_via_divide_floor;\n    api.abs_via_isNegative_negate= abs_via_isNegative_negate;\n    api.ceiling_via_floor        = ceiling_via_floor;\n    api.truncate_via_ceiling_floor= truncate_via_ceiling_floor;\n    api.round_via_floor_compare_isEven= round_via_floor_compare_isEven;\n\n    api.divideReduced_via_isUnit = divideReduced_via_isUnit;\n    api.Integer_divide_via_gcd_div= Integer_divide_via_gcd_div;\n    api.Integer_reciprocal_via_divideReduced\n        = Integer_reciprocal_via_divideReduced;\n    api.ExactRational_numberToString= ExactRational_numberToString;\n    api.Integer_numeratorAndDenominator= Integer_numeratorAndDenominator;\n\n    api.genericExp10             = genericExp10;\n    api.expt_N_EI_fn             = expt_N_EI_fn;\n    api.expt_N_EI                = expt_N_EI;\n    api.gcdNonnegative_via_isZero_mod= gcdNonnegative_via_isZero_mod;\n    api.bitwiseNot_via_subtract  = bitwiseNot_via_subtract;\n\n    api.Real_toFixed             = Real_toFixed;\n    api.Real_toExponential       = Real_toExponential;\n    api.Real_toPrecision         = Real_toPrecision;\n    api.Complex_valueOf          = Complex_valueOf;\n\n    return api;\n}\n\n\n/*\n    Function: installGenericFunctions(plugins)\n    <installGenericFunctions> specifies definitions of many generic\n    functions in terms of other generic facilities, reducing the\n    minimum requirements of number implementations.\n\n    Input:\n\n    *plugins* shall be a <PluginContainer> containing the output of\n    <defineGenericFunctions> and <implementPluginLibrary>\n\n    Output:\n\n    Output is in the form of generic function definitions using the\n    classes defined by <defineAbstractTypes>.\n*/\nfunction installGenericFunctions(plugins) {\n    "use strict";\n\n    var SchemeNumberType         = plugins.get("SchemeNumberType");\n    var Complex                  = plugins.get("Complex");\n    var Real                     = plugins.get("Real");\n    var InexactReal              = plugins.get("InexactReal");\n    var ExactReal                = plugins.get("ExactReal");\n    var ExactRational            = plugins.get("ExactRational");\n    var ExactInteger             = plugins.get("ExactInteger");\n\n    var raise = plugins.get("raise");\n    function def(generic, types, impl) {\n        var gen = plugins.get(generic);\n        if (!gen)\n            return;\n        var fn = undefined;\n        if (impl) {\n            fn = plugins.get(impl);\n            if (!fn) {\n                console.log(impl + " not defined");\n                return;\n            }\n        }\n        gen.def.apply(gen.def, types.concat(fn));\n    }\n\n    def("expt",      [SchemeNumberType, ExactInteger], "expt_N_EI");\n    def("square",    [SchemeNumberType], "square_via_multiply");\n    def("isInexact", [SchemeNumberType], "isInexact_via_isExact");\n    def("ne",        [SchemeNumberType, SchemeNumberType], "ne_via_eq");\n    def("subtract",  [SchemeNumberType, SchemeNumberType],\n        "subtract_via_negate_add");\n    def("divide",    [SchemeNumberType, SchemeNumberType],\n        "divide_via_reciprocal_multiply");\n\n    def("isComplex", [Complex], "retTrue");\n    def("numberToString", [Complex], "Complex_numberToString");\n    def("sqrt",      [Complex], "Complex_sqrt");\n    def("exp",       [Complex], "Complex_exp");\n    def("log",       [Complex], "Complex_log");\n    def("sin",       [Complex], "Complex_sin");\n    def("cos",       [Complex], "Complex_cos");\n    def("tan",       [Complex], "tan_via_divide_sin_cos");\n    def("asin",      [Complex], "Complex_asin");\n    def("acos",      [Complex], "Complex_acos");\n    def("atan",      [Complex], "Complex_atan");\n\n    def("toInexact", [Complex], "Complex_toInexact");\n    def("toExact",   [Complex], "Complex_toExact");\n    def("isZero",    [Complex], "Complex_isZero");\n    def("magnitude", [Complex], "Complex_magnitude");\n    def("angle",     [Complex], "Complex_angle");\n    def("eq",        [Complex, Complex], "Complex_eq");\n    def("eq",        [Complex, Real], "Complex_eq_Real");\n    def("eq",        [Real, Complex], "Real_eq_Complex");\n    def("ne",        [Complex, Complex], "Complex_ne");\n    def("ne",        [Complex, Real], "Complex_ne_Real");\n    def("ne",        [Real, Complex], "Real_ne_Complex");\n    def("add",       [Real, Complex], "Real_add_Complex");\n    def("add",       [Complex, Real], "Complex_add_Real");\n    def("add",       [Complex, Complex], "Complex_add");\n    def("subtract",  [Real, Complex], "Real_subtract_Complex");\n    def("subtract",  [Complex, Real], "Complex_subtract_Real");\n    def("subtract",  [Complex, Complex], "Complex_subtract");\n    def("negate",    [Complex], "Complex_negate");\n    def("multiply",  [Real, Complex], "Real_multiply_Complex");\n    def("multiply",  [Complex, Real], "Complex_multiply_Real");\n    def("multiply",  [Complex, Complex], "Complex_multiply");\n    def("divide",    [Complex, Real], "Complex_divide_Real");\n    def("square",    [Complex], "Complex_square");\n    def("reciprocal",[Complex], "Complex_reciprocal");\n    def("divide",    [Real, Complex], "Real_divide_Complex");\n    def("divide",    [Complex, Complex], "Complex_divide");\n\n    def("isReal",     [Real], "retTrue");\n    def("realPart",   [Real], "retThis");\n    def("imagPart",   [Real], "retZero");\n    def("conjugate",  [Real], "retThis");\n    def("isUnit",     [Real], "isUnit_via_eq");\n    def("magnitude",  [Real], "Real_magnitude_via_abs");\n    def("isPositive", [Real], "isPositive_via_sign");\n    def("isNegative", [Real], "isNegative_via_sign");\n    def("isZero",     [Real], "isZero_via_sign");\n    def("sign",       [Real], "sign_via_compare");\n    def("eq", [Real, Real], "eq_via_compare");\n    def("ne", [Real, Real], "ne_via_compare");\n    def("gt", [Real, Real], "gt_via_compare");\n    def("lt", [Real, Real], "lt_via_compare");\n    def("ge", [Real, Real], "ge_via_compare");\n    def("le", [Real, Real], "le_via_compare");\n    def("divAndMod",  [Real, Real], "divAndMod_via_divide_floor");\n    def("div",        [Real, Real], "div_via_divide_floor");\n    def("mod",        [Real, Real], "mod_via_divide_floor");\n    def("abs",        [Real], "abs_via_isNegative_negate");\n    def("ceiling",    [Real], "ceiling_via_floor");\n    def("truncate",   [Real], "truncate_via_ceiling_floor");\n    def("round",      [Real], "round_via_floor_compare_isEven");\n\n    def("isExact",   [InexactReal], "retFalse");\n    def("isInexact", [InexactReal], "retTrue");\n    def("toInexact", [InexactReal], "retThis");\n    def("angle",     [InexactReal], "InexactReal_angle_via_isNegative");\n\n    def("isExact",       [ExactReal], "retTrue");\n    def("isInexact",     [ExactReal], "retFalse");\n    def("toExact",       [ExactReal], "retThis");\n    def("SN_isNaN",      [ExactReal], "retFalse");\n    def("SN_isFinite",   [ExactReal], "retTrue");\n    def("SN_isInfinite", [ExactReal], "retFalse");\n    def("angle",         [ExactReal], "ExactReal_angle_via_isNegative");\n\n    def("isRational",     [ExactRational], "retTrue");\n    def("divideReduced",  [ExactInteger, ExactInteger],\n        "divideReduced_via_isUnit");\n    def("divide",   [ExactInteger, ExactInteger], "Integer_divide_via_gcd_div");\n    def("reciprocal", [ExactInteger], "Integer_reciprocal_via_divideReduced");\n\n    def("isInteger",      [ExactInteger], "retTrue");\n    def("numerator",      [ExactInteger], "retThis");\n    def("denominator",    [ExactInteger], "retOne");\n    def("floor",          [ExactInteger], "retThis");\n    def("ceiling",        [ExactInteger], "retThis");\n    def("round",          [ExactInteger], "retThis");\n    def("truncate",       [ExactInteger], "retThis");\n    def("exp10",          [ExactInteger], "genericExp10");\n    def("gcdNonnegative", [ExactInteger, ExactInteger],\n        "gcdNonnegative_via_isZero_mod");\n\n    def("bitwiseNot",     [ExactInteger], "bitwiseNot_via_subtract");\n\n    // The following expt definition is invalid for (ExactReal, ExactInteger)...\n    def("expt", [Complex, Complex], "Complex_expt");\n\n    // ... so override it.\n    def("expt", [ExactReal, ExactInteger], "expt_N_EI");\n\n    // Avoid lots of work for inexact bases.\n    def("expt", [Complex, ExactInteger], "complex_or_exact_expt");\n\n    def("numberToString", [ExactRational], "ExactRational_numberToString");\n    def("numberToString", [ExactInteger], undefined);\n    def("numeratorAndDenominator", [ExactInteger],\n        "Integer_numeratorAndDenominator");\n}\n\n\n/*\n    Function: installEcmaMethods(plugins)\n\n    <installEcmaMethods> defines the methods *toFixed*,\n    *toExponential*, and *toPrecision* (specified by ECMAScript for\n    *Number*) on exact reals.\n\n    It defines the *valueOf* method on class *Complex* in terms of the\n    same method on *Real*, but then overrides the method on *Real*\n    with a generic one returning *NaN* to avoid recursion.  Complex\n    *valueOf* returns *NaN* in every case except where the imaginary\n    part equals 0.  Thus, for example, *5.0+0.0i* converts to native\n    *5*.\n\n    *ExactReal*, *Complex*, and *Real*, from <defineAbstractTypes>,\n    are required when <installEcmaMethods> is called.  So are\n    *Real_toFixed*, *Real_toExponential*, *Real_toPrecision*,\n    *Complex_valueOf*, and *retNaN* from <implementPluginLibrary>.\n*/\nfunction installEcmaMethods(plugins) {\n    "use strict";\n    var N             = plugins.get("SchemeNumberType");\n    var ExactReal     = plugins.get("ExactReal");\n    var Complex       = plugins.get("Complex");\n    var Real          = plugins.get("Real");\n    var ExactRational = plugins.get("ExactRational");\n\n    // XXX should not install if not defined.\n\n    Complex.prototype.valueOf       = plugins.get("Complex_valueOf");\n    Complex.prototype.toString      = plugins.get("Complex_toString");\n    Complex.prototype.toFixed       = plugins.get("Complex_toFixed");\n    Complex.prototype.toExponential = plugins.get("Complex_toExponential");\n    Complex.prototype.toPrecision   = plugins.get("Complex_toPrecision");\n\n    // If Real inherits these from Complex, they will loop infinitely.\n    Real.prototype.valueOf        = N.prototype.valueOf;\n    Real.prototype.toFixed        = N.prototype.toFixed;\n    Real.prototype.toExponential  = N.prototype.toExponential;\n    Real.prototype.toPrecision    = N.prototype.toPrecision;\n    Real.prototype.toString       = N.prototype.toString;\n\n    ExactReal.prototype.toFixed       = plugins.get("Real_toFixed");\n    ExactReal.prototype.toExponential = plugins.get("Real_toExponential");\n    ExactReal.prototype.toPrecision   = plugins.get("Real_toPrecision");\n}\n\nfunction makeBase() {\n    var SchemeNumber = makeMinimalBase();\n    var plugins = SchemeNumber.plugins;\n\n    SchemeNumber.makeMinimalBase = makeMinimalBase;\n    SchemeNumber.makeBase = makeBase;\n\n    plugins.extend(implementPluginLibrary(plugins));\n    plugins.extend(defineAbstractTypes(plugins));\n    installAbstractTypes(plugins);\n    installStubFunctions(plugins);\n\n    installGenericFunctions(plugins);\n    installEcmaMethods(plugins);\n\n    return SchemeNumber;\n}\n\n/*\n    Function: installDefaultExactInteger(plugins, convert)\n    Allows multiple exact integer implementations to interoperate\n    via conversion to a default one.\n\n    *convert* must be a function that accepts an ExactInteger and\n    returns an equivalent value of standard type.  The following\n    generic functions must be specialized for the standard type:\n    compare add subtract multiply expt divAndMod div mod.\n*/\nfunction installDefaultExactInteger(plugins, convert) {\n    var ExactInteger = plugins.get("ExactInteger");\n\n    function def(name) {\n        var func = plugins.get(name);\n        function EI_func(n) {\n            return func(convert(this), convert(n));\n        }\n        func.def(ExactInteger, ExactInteger, EI_func);\n    }\n\n    // XXX Should avoid defining on ExactInteger ops that the\n    // implementation class does not specialize.\n    def("compare");\n    def("add");\n    def("subtract");\n    def("multiply");\n    def("expt");\n    def("divAndMod");\n    def("div");\n    def("mod");\n    def("gcdNonnegative");\n\n    plugins.extend("canonicalExactInteger", convert);\n}\n\nfunction installDefaultRational(plugins, convert, divideReduced) {\n    var ExactInteger = plugins.get("ExactInteger");\n    var ExactRational = plugins.get("ExactRational");\n\n    function def(name) {\n        var func = plugins.get(name);\n        function EQ_func(n) {\n            return func(convert(this), convert(n));\n        }\n        func.def(ExactRational, ExactRational, EQ_func);\n    }\n\n    // XXX Should avoid defining on ExactRational ops that the\n    // implementation class does not specialize.\n    def("compare");\n    def("add");\n    def("subtract");\n    def("multiply");\n    def("divide");\n\n    function EI_divideReduced(n) {\n        return divideReduced(this, n);\n    }\n\n    plugins.get("divideReduced").def(ExactInteger, ExactInteger,\n                                     EI_divideReduced);\n\n    plugins.extend("canonicalRational", convert);\n}\n\n/*\n    Function: implementNativeInexactReal(plugins)\n    Returns a collection of functions implementing inexact reals as\n    native numbers.\n\n    The functions return native numbers wrapped in a\n    <NativeInexactReal> object.  The object trivially implements the\n    standard *toString* and formatting methods by forwarding them to\n    the corresponding functions from *Number.prototype*.  The purpose\n    of wrapping numbers this way is to provide a method space other\n    than *Number.prototype* in which to insert properties supporting\n    Scheme functions.\n\n    Output:\n\n    parseInexact - function(sign, string) -> SchemeNumber\n    As required by <implementPluginLibrary>.\n\n    nativeToInexact - function(number) -> SchemeNumber\n    As required by <implementSchemeNumber>.\n\n    NativeInexactReal - constructor of values returned by functions\n    defined in <implementNativeInexactReal>.  Inherits from\n    <InexactReal>.\n\n    NativeInexactReal_debug - function() -> string\n    Specialization of the <debug> function for the <NativeInexactReal>\n    type.\n\n    Native_log - function(number) -> SchemeNumber\n    Returns the log of *number* as a <NativeInexactReal>.\n\n    Native_sqrt - function(number) -> SchemeNumber\n    Returns the sqrt of *number* as a <NativeInexactReal>.\n\n    Native_atan2 - function(y, x) -> SchemeNumber\n    *y* and *x* are native numbers.  Returns *atan2(y, x)* as a\n    <NativeInexactReal>.\n\n    Native_atan - function(number) -> SchemeNumber\n    Returns the atan of *number* as a <NativeInexactReal>.\n\n    Native_cos - function(number) -> SchemeNumber\n    Returns the cos of *number* as a <NativeInexactReal>.\n\n    Native_sin - function(number) -> SchemeNumber\n    Returns the sin of *number* as a <NativeInexactReal>.\n\n    Native_tan - function(number) -> SchemeNumber\n    Returns the tan of *number* as a <NativeInexactReal>.\n\n    Native_exp - function(number) -> SchemeNumber\n    Returns the exp of *number* as a <NativeInexactReal>.\n\n    Native_abs - function(number) -> SchemeNumber\n    Returns the abs of *number* as a <NativeInexactReal>.\n\n    Native_floor - function(number) -> SchemeNumber\n    Returns the floor of *number* as a <NativeInexactReal>.\n\n    Native_ceil - function(number) -> SchemeNumber\n    Returns the ceil of *number* as a <NativeInexactReal>.\n\n    Native_pow - function(base, power) -> SchemeNumber\n    *base* and *power* are native numbers.  Returns the *number* to\n    the *power* as a <NativeInexactReal>.\n\n    Flonum_debug - function() -> string\n*/\nfunction implementNativeInexactReal(plugins) {\n    "use strict";\n    var g = plugins.get("es5globals");\n    var uncurry = plugins.get("uncurry");\n    var InexactReal = plugins.get("InexactReal");\n    var api = g.Object.create(null);\n\n    var Number_toFixed        = uncurry(g.Number.prototype.toFixed);\n    var Number_toExponential  = uncurry(g.Number.prototype.toExponential);\n    var Number_toPrecision    = uncurry(g.Number.prototype.toPrecision);\n    var Number_toString       = uncurry(g.Number.prototype.toString);\n    var Number_toLocaleString = uncurry(g.Number.prototype.toLocaleString);\n    var _parseFloat = g.parseFloat;\n\n    function NativeInexactReal(x) {\n        this._ = x;\n    }\n    NativeInexactReal.prototype = new InexactReal();\n\n    function NativeInexactReal_debug() {\n        return "NativeInexact(" + this._ + ")";\n    }\n\n    function valueOf() {\n        return this._;\n    }\n    function toFixed(digits) {\n        return Number_toFixed(this._, digits);\n    }\n    function toExponential(digits) {\n        return Number_toExponential(this._, digits);\n    }\n    function toPrecision(precision) {\n        return Number_toPrecision(this._, precision);\n    }\n    function toString(radix) {\n        return Number_toString(this._, radix);\n    }\n    function toLocaleString() {\n        return Number_toLocaleString(this._);\n    }\n\n    NativeInexactReal.prototype.valueOf        = valueOf;\n    NativeInexactReal.prototype.toFixed        = toFixed;\n    NativeInexactReal.prototype.toExponential  = toExponential;\n    NativeInexactReal.prototype.toPrecision    = toPrecision;\n    NativeInexactReal.prototype.toString       = toString;\n    NativeInexactReal.prototype.toLocaleString = toLocaleString;\n\n    var Flonum = NativeInexactReal;\n\n    var INEXACT_ZERO = new NativeInexactReal(0);\n    function nativeToInexact(x) {\n        //assert(typeof x === "number");\n        return (x === 0 ? INEXACT_ZERO : new NativeInexactReal(x));\n    }\n\n    function parseInexact(sign, string) {\n        return nativeToInexact(sign * _parseFloat(string));\n    }\n\n    function defNative(name) {\n        var math = g.Math[name];\n        function nativeMath1(a) {\n            return nativeToInexact(math(a));\n        }\n        function nativeMath2(a, b) {\n            return nativeToInexact(math(a, b));\n        }\n        api["Native_" + name] = (math.length === 1 ? nativeMath1 : nativeMath2);\n    }\n\n    defNative("log");\n    defNative("sqrt");\n    defNative("atan2");\n    defNative("atan");\n    defNative("cos");\n    defNative("sin");\n    defNative("tan");\n    defNative("exp");\n    defNative("abs");\n    defNative("floor");\n    defNative("ceil");\n    defNative("pow");\n\n    api.parseInexact             = parseInexact;\n    api.nativeToInexact          = nativeToInexact;\n    api.NativeInexactReal        = NativeInexactReal;\n    api.NativeInexactReal_debug  = NativeInexactReal_debug;\n    return api;\n}\n\n/*\n// Flonums as bare primitives, for people who don\'t mind adding\n// properties to Number.prototype.\nfunction implementPrimitiveInexactReal(plugins) {\n    "use strict";\n    var g = plugins.get("es5globals");\n    var uncurry = plugins.get("uncurry");\n    var api = g.Object.create(null);\n\n    function parseInexact(sign, string) {\n        return sign * _parseFloat(string);\n    }\n\n    function Number_debug() {\n        return "PrimitiveInexact(" + this + ")";\n    }\n\n    function defNative(name) {\n        api["Native_" + name] = g.Math[name];\n    }\n\n    defNative("log");\n    defNative("sqrt");\n    defNative("atan2");\n    defNative("atan");\n    defNative("cos");\n    defNative("sin");\n    defNative("tan");\n    defNative("exp");\n    defNative("abs");\n    defNative("floor");\n    defNative("ceil");\n    defNative("pow");\n\n    api.parseInexact             = parseInexact;\n    api.nativeToInexact          = Number;\n    api.NativeInexactReal        = Number;\n    api.NativeInexactReal_debug  = Number_debug;\n    return api;\n}\n*/\n\n/*\n    Function: implementNativeFlonumLibrary(plugins)\n    Creates functions operating on Scheme inexact reals.\n\n    The functions convert their arguments to native numbers using "+"\n    (which invokes *valueOf()* when the arguments are not primitive\n    numbers).\n\n    Real_toInexact_via_primitive - function() -> InexactReal\n\n    Flonum_add XXX incomplete.\n*/\nfunction implementNativeFlonumLibrary(plugins) {\n    "use strict";\n    var g = plugins.get("es5globals");\n    var uncurry = plugins.get("uncurry");\n    var api = g.Object.create(null);\n\n    var String_indexOf   = uncurry(g.String.prototype.indexOf);\n    var String_substring = uncurry(g.String.prototype.substring);\n    var String_replace   = uncurry(g.String.prototype.replace);\n    var Number_toString  = uncurry(g.Number.prototype.toString);\n\n    // Squirrel away the native math library.  XXX could trim unused items.\n    var Math_E       = g.Math.E;\n    var Math_LN10    = g.Math.LN10;\n    var Math_LN2     = g.Math.LN2;\n    var Math_LOG2E   = g.Math.LOG2E;\n    var Math_LOG10E  = g.Math.LOG10E;\n    var Math_PI      = g.Math.PI;\n    var Math_SQRT1_2 = g.Math.SQRT1_2;\n    var Math_SQRT2   = g.Math.SQRT2;\n    var Math_abs     = g.Math.abs;\n    var Math_acos    = g.Math.acos;\n    var Math_asin    = g.Math.asin;\n    var Math_atan    = g.Math.atan;\n    var Math_atan2   = g.Math.atan2;\n    var Math_ceil    = g.Math.ceil;\n    var Math_cos     = g.Math.cos;\n    var Math_exp     = g.Math.exp;\n    var Math_floor   = g.Math.floor;\n    var Math_log     = g.Math.log;\n    var Math_max     = g.Math.max;\n    var Math_min     = g.Math.min;\n    var Math_pow     = g.Math.pow;\n    var Math_random  = g.Math.random;\n    var Math_round   = g.Math.round;\n    var Math_sin     = g.Math.sin;\n    var Math_sqrt    = g.Math.sqrt;\n    var Math_tan     = g.Math.tan;\n\n    var _isFinite    = g.isFinite;\n    var _isNaN       = g.isNaN;\n    var _parseFloat  = g.parseFloat;\n    var _undefined   = g.undefined;\n    var _Number      = g.Number;\n\n    var nativeToInexact, Native_log, Native_sqrt, Native_atan2,\n        Native_atan, Native_cos, Native_sin, Native_tan, Native_exp,\n        Native_abs, Native_floor, Native_ceil, Native_pow;\n    var raise, inexactRectangular, INEXACT_ZERO, nativeToExactInteger, TWO, divideReducedNotByOne, numberToString, isExact, isInexact, toExact, toInexact, isRational, isInteger, isZero, negate, square, eq, ne, add, subtract, multiply, divide, expt, exp, sqrt, log, asin, acos, atan, sin, cos, tan, abs, isPositive, isNegative, sign, floor, ceiling, truncate, round, compare, gt, lt, ge, le, divAndMod, div, mod, atan2, numerator, denominator, isEven, isOdd, Complex_expt_fn, Complex_acos_fn, Complex_asin_fn, Complex_log_fn, numberToBinary, nativeDenominatorLog2, nativeDenominator;\n\n    function onPluginsChanged(plugins) {\n        // XXX Could require these prior to call.\n        nativeToInexact          = plugins.get("nativeToInexact");\n        Native_log               = plugins.get("Native_log");\n        Native_sqrt              = plugins.get("Native_sqrt");\n        Native_atan2             = plugins.get("Native_atan2");\n        Native_atan              = plugins.get("Native_atan");\n        Native_cos               = plugins.get("Native_cos");\n        Native_sin               = plugins.get("Native_sin");\n        Native_tan               = plugins.get("Native_tan");\n        Native_exp               = plugins.get("Native_exp");\n        Native_abs               = plugins.get("Native_abs");\n        Native_floor             = plugins.get("Native_floor");\n        Native_ceil              = plugins.get("Native_ceil");\n        Native_pow               = plugins.get("Native_pow");\n\n        raise                    = plugins.get("raise");\n        inexactRectangular       = plugins.get("inexactRectangular");\n        INEXACT_ZERO             = plugins.get("INEXACT_ZERO");\n        nativeToExactInteger     = plugins.get("nativeToExactInteger");\n        divideReducedNotByOne    = plugins.get("divideReducedNotByOne");\n        TWO                      = plugins.get("TWO");\n\n        numberToString           = plugins.get("numberToString");\n        isExact                  = plugins.get("isExact");\n        isInexact                = plugins.get("isInexact");\n        toExact                  = plugins.get("toExact");\n        toInexact                = plugins.get("toInexact");\n        isRational               = plugins.get("isRational");\n        isInteger                = plugins.get("isInteger");\n        isZero                   = plugins.get("isZero");\n        negate                   = plugins.get("negate");\n        square                   = plugins.get("square");\n        eq                       = plugins.get("eq");\n        ne                       = plugins.get("ne");\n        add                      = plugins.get("add");\n        subtract                 = plugins.get("subtract");\n        multiply                 = plugins.get("multiply");\n        divide                   = plugins.get("divide");\n        expt                     = plugins.get("expt");\n        exp                      = plugins.get("exp");\n        sqrt                     = plugins.get("sqrt");\n        log                      = plugins.get("log");\n        asin                     = plugins.get("asin");\n        acos                     = plugins.get("acos");\n        atan                     = plugins.get("atan");\n        sin                      = plugins.get("sin");\n        cos                      = plugins.get("cos");\n        tan                      = plugins.get("tan");\n        abs                      = plugins.get("abs");\n        isPositive               = plugins.get("isPositive");\n        isNegative               = plugins.get("isNegative");\n        sign                     = plugins.get("sign");\n        floor                    = plugins.get("floor");\n        ceiling                  = plugins.get("ceiling");\n        truncate                 = plugins.get("truncate");\n        round                    = plugins.get("round");\n        compare                  = plugins.get("compare");\n        gt                       = plugins.get("gt");\n        lt                       = plugins.get("lt");\n        ge                       = plugins.get("ge");\n        le                       = plugins.get("le");\n        divAndMod                = plugins.get("divAndMod");\n        div                      = plugins.get("div");\n        mod                      = plugins.get("mod");\n        atan2                    = plugins.get("atan2");\n        numerator                = plugins.get("numerator");\n        denominator              = plugins.get("denominator");\n        isEven                   = plugins.get("isEven");\n        isOdd                    = plugins.get("isOdd");\n\n        Complex_expt_fn          = plugins.get("Complex_expt_fn");\n        Complex_acos_fn          = plugins.get("Complex_acos_fn");\n        Complex_asin_fn          = plugins.get("Complex_asin_fn");\n        Complex_log_fn           = plugins.get("Complex_log_fn");\n        numberToBinary           = plugins.get("numberToBinary");\n        nativeDenominatorLog2    = plugins.get("nativeDenominatorLog2");\n        nativeDenominator        = plugins.get("nativeDenominator");\n    }\n    plugins.onChange.subscribe(onPluginsChanged);\n    onPluginsChanged(plugins);\n\n    function Real_toInexact_via_Flonum() {\n        return nativeToInexact(Number(this));\n    }\n\n    function Flonum_numberToString(radix, precision) {\n        var t = (+this);\n        if (radix && radix != 10 && _isFinite(t))\n            return "#i" + numberToString(toExact(this), radix);\n\n        if (!_isFinite(t)) {\n            if (_isNaN(t))\n                return("+nan.0");\n            return (t > 0 ? "+inf.0" : "-inf.0");\n        }\n\n        var s = Number_toString(t);\n\n        if (String_indexOf(s, \'.\') === -1) {\n            // Force the result to contain a decimal point as per R6RS.\n            var e = String_indexOf(s, \'e\');\n            if (e === -1)\n                s += ".";\n            else\n                s = (String_substring(s, 0, e) + "." +\n                     String_substring(s, e));\n        }\n\n        if (precision != _undefined) {\n            if (precision < 53) {\n                var bits = String_replace(\n                    String_replace(\n                        String_replace(\n                            numberToBinary(+this),\n                                /[-+.]/g, ""),\n                            /^0+/, ""),\n                        /0+$/, "").length;\n                if (precision < bits)\n                    precision = bits;\n            }\n            s += "|" + precision;\n        }\n\n        return s;\n    }\n\n    function Flonum_denominator() {\n        var t = (+this);\n        if (!_isFinite(t))\n            raise("&assertion", "not a rational number", t);\n        return Native_pow(2, nativeDenominatorLog2(t));\n    }\n\n    function Flonum_numerator() {\n        var t = (+this);\n        if (!_isFinite(t))\n            raise("&assertion", "not a rational number", t);\n        return nativeToInexact(this * nativeDenominator(t));\n    }\n\n    function Flonum_isInteger() {\n        var t = (+this);\n        return _isFinite(t) && t === Math_floor(t);\n    }\n\n    function Flonum_SN_isFinite() {\n        return _isFinite(+this);\n    }\n\n    function Flonum_SN_isInfinite() {\n        var t = (+this);\n        return !_isFinite(t) && !_isNaN(t);\n    }\n\n    function Flonum_SN_isNaN() {\n        return _isNaN(+this);\n    }\n\n    function Flonum_isZero()     { return (+this) === 0; }\n    function Flonum_isPositive() { return (+this) > 0; }\n    function Flonum_isNegative() { return (+this) < 0; }\n\n    function Flonum_sign() {\n        var t = (+this);\n        return (t === 0 ? 0 : (t > 0 ? 1 : -1));\n    }\n\n    function Flonum_isEven() {\n        //assert(Flonum_isInteger(this))\n        return ((+this) & 1) === 0;\n    }\n\n    function Flonum_isOdd() {\n        //assert(Flonum_isInteger(this))\n        return ((+this) & 1) === 1;\n    }\n\n    function Flonum_eq(x) { return (+this) === (+x); }\n    function Flonum_ne(x) { return (+this) !== (+x); }\n    function Flonum_gt(x) { return (+this) > (+x); }\n    function Flonum_lt(x) { return (+this) < (+x); }\n    function Flonum_ge(x) { return (+this) >= (+x); }\n    function Flonum_le(x) { return (+this) <= (+x); }\n\n    function Flonum_compare(x) {\n        var t = (+this);\n        x = (+x);\n        if (t === x) return 0;\n        if (t < x) return -1;\n        if (t > x) return 1;\n        return NaN;\n    }\n\n    function Flonum_toExact() {\n        var x = (+this);\n\n        if (!_isFinite(x))\n            raise("&implementation-violation",\n                  "inexact argument has no reasonably close exact equivalent",\n                  this);\n\n        var d = nativeDenominator(x);\n        var n;\n\n        if (d === 1)\n            return nativeToExactInteger(x);\n\n        if (_isFinite(d)) {\n            n = x * d;\n            d = nativeToExactInteger(d);\n        }\n        else {\n            // Denormal x.\n            var dl2 = nativeDenominatorLog2(x);\n            n = x * 9007199254740992;\n            n *= natPow(2, dl2 - 53);\n            d = expt(TWO, nativeToExactInteger(dl2));\n        }\n        //assert(_isFinite(n));\n        return divideReducedNotByOne(nativeToExactInteger(n), d);\n    }\n\n    function Flonum_add(x)      { return nativeToInexact((+this) + (+x)); }\n    function Flonum_subtract(x) { return nativeToInexact((+this) - (+x)); }\n    function Flonum_multiply(x) { return nativeToInexact((+this) * (+x)); }\n    function Flonum_divide(x)   { return nativeToInexact((+this) / (+x)); }\n\n    function Flonum_negate() {\n        return nativeToInexact(-(+this));\n    }\n\n    function Flonum_abs() {\n        return nativeToInexact(Math_abs(+this));\n    }\n\n    function Flonum_reciprocal() {\n        return nativeToInexact(1 / (+this));\n    }\n\n    function div_native(x, y) {\n        //assert(_isFinite(x));\n        //assert(y != 0);\n        if (y > 0)\n            return Math_floor(x / y);\n        if (y < 0)\n            return Math_ceil(x / y);\n        return NaN;\n    }\n    function Flonum_divAndMod(y) {\n        var x = (+this);\n        y = (+y);\n        var div = div_native(x, y);\n        return [nativeToInexact(div), nativeToInexact(x - (y * div))];\n    }\n    function Flonum_div(y) {\n        var x = (+this);\n        y = (+y);\n        return nativeToInexact(div_native(x, y));\n    }\n    function Flonum_mod(y) {\n        var x = (+this);\n        y = (+y);\n        return nativeToInexact(x - y * div_native(x, y));\n    }\n\n    function Flonum_square() {\n        var t = (+this);\n        return nativeToInexact(t * t);\n    }\n\n    function Flonum_expt(x) {\n        // Return this number to the power of x.\n        var t = (+this);\n        if (t < 0)\n            return Complex_expt_fn(this, x);\n        return Native_pow(t, x);\n    }\n\n    function Flonum_round() {\n        var t = (+this);\n        var ret = Math_floor(t);\n        var diff = t - ret;\n        if (diff < 0.5) return nativeToInexact(ret);\n        if (diff > 0.5) return nativeToInexact(ret + 1);\n        return nativeToInexact(2 * Math_round(t / 2));\n    }\n\n    function Flonum_truncate() {\n        var t = (+this);\n        return (t < 0 ? Native_ceil(t) : Native_floor(t));\n    }\n\n    function funcToMeth(fn) {\n        return function() {\n            return fn(+this);\n        };\n    }\n\n    var Flonum_ceiling = funcToMeth(Native_ceil);\n    var Flonum_floor   = funcToMeth(Native_floor);\n\n    // These functions are always allowed to return inexact.  We, however,\n    // override a few of these in ZERO and ONE.\n    // sqrt exp log sin cos tan asin acos atan atan2\n\n    var Flonum_atan = funcToMeth(Native_atan);\n    var Flonum_cos  = funcToMeth(Native_cos);\n    var Flonum_exp  = funcToMeth(Native_exp);\n    var Flonum_sin  = funcToMeth(Native_sin);\n    var Flonum_tan  = funcToMeth(Native_tan);\n\n    function cplxFuncToMeth(mathFunc, complexFunc) {\n        return function() {\n            var t = (+this);\n            var ret = mathFunc(t);\n            if (_isNaN(ret))\n                return complexFunc(this);\n            return nativeToInexact(ret);\n        };\n    }\n    var Flonum_acos = cplxFuncToMeth(Math_acos, Complex_acos_fn);\n    var Flonum_asin = cplxFuncToMeth(Math_asin, Complex_asin_fn);\n\n    function Flonum_log() {\n        var x = (+this);\n        if (x < 0)\n            return Complex_log_fn(this);\n        return Native_log(x);\n    }\n\n    function Flonum_sqrt() {\n        var x = (+this);\n        if (x >= 0)\n            return Native_sqrt(x);\n        if (_isNaN(x))\n            return nativeToInexact(x);\n        return inexactRectangular(INEXACT_ZERO, Native_sqrt(-x));\n    }\n\n    function Flonum_atan2(x) {\n        return Native_atan2((+this), x);\n    }\n\n    api.Real_toInexact_via_Flonum= Real_toInexact_via_Flonum;\n    api.Flonum_numberToString    = Flonum_numberToString;\n    api.Flonum_isRational        = Flonum_SN_isFinite;\n    api.Flonum_denominator       = Flonum_denominator;\n    api.Flonum_numerator         = Flonum_numerator;\n    api.Flonum_isInteger         = Flonum_isInteger;\n    api.Flonum_SN_isFinite       = Flonum_SN_isFinite;\n    api.Flonum_SN_isInfinite     = Flonum_SN_isInfinite;\n    api.Flonum_SN_isNaN          = Flonum_SN_isNaN;\n    api.Flonum_isZero            = Flonum_isZero;\n    api.Flonum_isPositive        = Flonum_isPositive;\n    api.Flonum_isNegative        = Flonum_isNegative;\n    api.Flonum_sign              = Flonum_sign;\n    api.Flonum_isEven            = Flonum_isEven;\n    api.Flonum_isOdd             = Flonum_isOdd;\n    api.Flonum_eq                = Flonum_eq;\n    api.Flonum_ne                = Flonum_ne;\n    api.Flonum_gt                = Flonum_gt;\n    api.Flonum_lt                = Flonum_lt;\n    api.Flonum_ge                = Flonum_ge;\n    api.Flonum_le                = Flonum_le;\n    api.Flonum_compare           = Flonum_compare;\n    api.Flonum_toExact           = Flonum_toExact;\n    api.Flonum_add               = Flonum_add;\n    api.Flonum_subtract          = Flonum_subtract;\n    api.Flonum_multiply          = Flonum_multiply;\n    api.Flonum_divide            = Flonum_divide;\n    api.Flonum_negate            = Flonum_negate;\n    api.Flonum_abs               = Flonum_abs;\n    api.Flonum_reciprocal        = Flonum_reciprocal;\n    api.Flonum_divAndMod         = Flonum_divAndMod;\n    api.Flonum_div               = Flonum_div;\n    api.Flonum_mod               = Flonum_mod;\n    api.Flonum_square            = Flonum_square;\n    api.Flonum_expt              = Flonum_expt;\n    api.Flonum_round             = Flonum_round;\n    api.Flonum_truncate          = Flonum_truncate;\n    api.Flonum_ceiling           = Flonum_ceiling;\n    api.Flonum_floor             = Flonum_floor;\n    api.Flonum_atan              = Flonum_atan;\n    api.Flonum_cos               = Flonum_cos;\n    api.Flonum_exp               = Flonum_exp;\n    api.Flonum_sin               = Flonum_sin;\n    api.Flonum_tan               = Flonum_tan;\n    api.Flonum_acos              = Flonum_acos;\n    api.Flonum_asin              = Flonum_asin;\n    api.Flonum_log               = Flonum_log;\n    api.Flonum_sqrt              = Flonum_sqrt;\n    api.Flonum_atan2             = Flonum_atan2;\n    return api;\n}\n\n/*\n    Function: installFlonum(plugins)\n\n    // XXX documentation out of date.\n\n    If *args* contains property *isDefaultInexactReal* with a true\n    value, <install> creates <pluginApi> operations as follows.\n\n    - The comparison operators (<eq>, <ne>, <gt>, <lt>, <ge>, <le>,\n      and <compare>) may convert their arguments to native numbers and\n      use native comparison when both are real and at least one is\n      inexact.\n\n    - The operators <add>, <subtract>, <multiply>, <divide>,\n      <divAndMod>, <div>, <mod>, and <expt> may return an object\n      created by this implementation when both arguments are real and\n      at least one is inexact.\n\n    - The operators <toInexact>, <atan>, <atan2>, <cos>, <exp>, <sin>,\n      <tan>, <acos>, <asin>, <log>, and <sqrt> may return an object\n      created by this implementation when passed any real arguments.\n*/\nfunction installFlonum(plugins) {\n    "use strict";\n    var Flonum                   = plugins.get("Flonum");\n    var Real                     = plugins.get("Real");\n    var InexactReal              = plugins.get("InexactReal");\n    var ExactReal                = plugins.get("ExactReal");\n    var i;\n    var isDefaultFlonum = true;  // XXX should make it an option.\n\n    // Augment Number.prototype if passed Number as Flonum.\n    if (!(Flonum.prototype instanceof InexactReal)) {\n        for (i in InexactReal.prototype)\n            if (!(i in Flonum.prototype))\n                Flonum.prototype[i] = InexactReal.prototype[i];\n    }\n\n    if (isDefaultFlonum) {\n        plugins.get("toInexact").def(ExactReal, plugins.get(\n            "Real_toInexact_via_Flonum"));\n    }\n\n    function def1_Flonum(name) {\n        var impl = plugins.get("Flonum_" + name);\n        if (!impl)\n            console.log("Flonum_" + name + " not defined");\n        plugins.get(name).def(Flonum, impl);\n    }\n    function def1_InexactReal(name) {\n        var impl = plugins.get("Flonum_" + name);\n        if (!impl)\n            console.log("Flonum_" + name + " not defined");\n        plugins.get(name).def(InexactReal, impl);\n    }\n    function def1_Real(name) {\n        var impl = plugins.get("Flonum_" + name);\n        if (!impl)\n            console.log("Flonum_" + name + " not defined");\n        plugins.get(name).def(Real, impl);\n    }\n\n    function def2_base(name) {\n        var generic = plugins.get(name);\n        var impl = plugins.get("Flonum_" + name);\n        if (!impl)\n            console.log("Flonum_" + name + " not defined");\n        generic.def(Flonum, Flonum, impl);\n    }\n    function def2_Flonum(name) {\n        var generic = plugins.get(name);\n        var impl = plugins.get("Flonum_" + name);\n        def2_base(name);\n        generic.def(ExactReal, Flonum, impl);\n        generic.def(Flonum, ExactReal, impl);\n    }\n    function def2_InexactReal(name) {\n        var generic = plugins.get(name);\n        var impl = plugins.get("Flonum_" + name);\n        def2_base(name);\n        generic.def(Real, InexactReal, impl);\n        generic.def(InexactReal, Real, impl);\n    }\n    function def2_Real(name) {\n        var generic = plugins.get(name);\n        var impl = plugins.get("Flonum_" + name);\n        def2_base(name);\n        generic.def(Real, Real, impl);\n    }\n\n    var def1inexact = (isDefaultFlonum ? def1_InexactReal : def1_Flonum);\n    var def1real    = (isDefaultFlonum ? def1_Real        : def1_Flonum);\n    var def2inexact = (isDefaultFlonum ? def2_InexactReal : def2_Flonum);\n    var def2real    = (isDefaultFlonum ? def2_Real        : def2_Flonum);\n\n    // "real" functions may convert their arguments to inexact.\n    // "inexact" functions operate only on inexact arguments.\n\n    def1inexact("numberToString");\n    def1inexact("isRational");\n    def1inexact("denominator");\n    def1inexact("numerator");\n    def1inexact("isInteger");\n    def1inexact("SN_isFinite");\n    def1inexact("SN_isInfinite");\n    def1inexact("SN_isNaN");\n    def1inexact("isZero");\n    def1inexact("isPositive");\n    def1inexact("isNegative");\n    def1inexact("sign");\n    def1inexact("isEven");\n    def1inexact("isOdd");\n    def1inexact("toExact");\n    def1inexact("negate");\n    def1inexact("abs");\n    def1inexact("reciprocal");\n    def1inexact("square");\n    def1inexact("round");\n    def1inexact("truncate");\n    def1inexact("ceiling");\n    def1inexact("floor");\n\n    def1real("atan");\n    def1real("cos");\n    def1real("exp");\n    def1real("sin");\n    def1real("tan");\n    def1real("acos");\n    def1real("asin");\n    def1real("log");\n    def1real("sqrt");\n\n    def2inexact("eq");\n    def2inexact("ne");\n    def2inexact("gt");\n    def2inexact("lt");\n    def2inexact("ge");\n    def2inexact("le");\n    def2inexact("compare");\n    def2inexact("add");\n    def2inexact("subtract");\n    def2inexact("multiply");\n    def2inexact("divide");\n    def2inexact("divAndMod");\n    def2inexact("div");\n    def2inexact("mod");\n\n    def2real("expt");  // XXX should be def2inexact?\n    def2real("atan2");\n}\n\n/*\n    Function: implementBigInteger(plugins, BigInteger)\n    Exact integer implementation that uses Matthew Crumley\'s BigInteger.\n*/\nfunction implementBigInteger(plugins, BigInteger) {\n    "use strict";\n    var g                        = plugins.get("es5globals");\n    var uncurry                  = plugins.get("uncurry");\n    var SchemeNumber             = plugins.get("SchemeNumber");\n    var BigIntegerName           = BigInteger.name || "BigInteger";\n    var Number_toString = uncurry(g.Number.prototype.toString);\n    var String_replace  = uncurry(g.String.prototype.replace);\n    var Array_concat    = uncurry(g.Array.prototype.concat);\n    var Array_map       = uncurry(g.Array.prototype.map);\n\n    var Math_LN10    = g.Math.LN10;\n    var Math_LN2     = g.Math.LN2;\n    var Math_abs     = g.Math.abs;\n    var Math_exp     = g.Math.exp;\n    var Math_floor   = g.Math.floor;\n    var Math_pow     = g.Math.pow;\n    var Math_sqrt    = g.Math.sqrt;\n\n    var api = g.Object.create(null);\n    var toBigInteger = plugins.get("Dispatch").defGeneric(\n        "to" + BigIntegerName, 1);\n\n    var raise, numberToString, negate, reciprocal, divide, sign, exp10, nativeToInexact, inexactRectangular, ZERO, ONE, MINUS_ONE, _2_32, PI, INEXACT_ZERO;\n\n    raise                    = plugins.get("raise");\n\n    numberToString           = plugins.get("numberToString");\n    negate                   = plugins.get("negate");\n    reciprocal               = plugins.get("reciprocal");\n    divide                   = plugins.get("divide");\n    sign                     = plugins.get("sign");\n    sign                     = plugins.get("sign");\n    exp10                    = plugins.get("exp10");\n\n    _2_32 = nativeToExactInteger(4294967296);\n\n    function onPluginsChanged(plugins, changed) {\n        nativeToInexact          = plugins.get("nativeToInexact");\n        inexactRectangular       = plugins.get("inexactRectangular");\n        ZERO                     = plugins.get("ZERO");\n        ONE                      = plugins.get("ONE");\n        MINUS_ONE                = plugins.get("MINUS_ONE");\n        PI                       = plugins.get("PI");\n        INEXACT_ZERO             = plugins.get("INEXACT_ZERO");\n    }\n    plugins.onChange.subscribe(onPluginsChanged);\n    onPluginsChanged(plugins);\n\n    function BigInteger_debug() {\n        return BigIntegerName + "(" + this.toString() + ")";\n    }\n\n    function parseExactInteger(sign, string, radix) {\n        // Trim leading zeroes to avoid BigInteger treating "0c" and\n        // "0b" as radix prefixes.\n        var n = BigInteger.parse(String_replace(string, /^0+/, ""), radix);\n        if (sign < 0)\n            n = n.negate();\n        return n;\n    }\n\n    function nativeToExactInteger(n) {\n        // Use base 16 to avoid exponential notation.\n        return BigInteger.parse(Number_toString(n, 16), 16);\n    }\n\n    function ExactInteger_toBigInteger() {\n        return BigInteger.parse(numberToString(this));\n    }\n\n    function integerTooBig(digits) {\n        raise("&implementation-restriction",\n              "exact integer would exceed limit of " +\n              (+SchemeNumber.maxIntegerDigits) +\n              " digits; adjust SchemeNumber.maxIntegerDigits",\n              digits);\n    }\n\n    // (expt *this* *p*)\n    function BigInteger_expt(p) {\n        if (this.isZero())\n            return (p.isZero() ? ONE : this);\n        if (this.isUnit()) {\n            if (this.isPositive())\n                return this;\n            return (p.isEven() ? ONE : this);\n        }\n\n        // If p != p.valueOf() due to inexactness, our result would\n        // exhaust memory, since |this| is at least 2.\n        // XXX does not respect maxIntegerDigits.\n        p = p.valueOf();\n        var a = this.pow(Math_abs(p));\n        return (p >= 0 ? a : reciprocal(a));\n    }\n\n    function BigInteger_numberToString(radix) {\n        return this.toString(radix);\n    }\n\n    function divAndMod_BigInteger(n, d) {\n        var dm = n.divRem(d);\n        if (dm[1].isNegative()) {\n            if (d.isNegative())\n                return [dm[0].next(), dm[1].subtract(d)];\n            return [dm[0].prev(), dm[1].add(d)];\n        }\n        return dm;\n    }\n\n    function BigInteger_divAndMod(d) {\n        return divAndMod_BigInteger(this, d);\n    }\n    function BigInteger_div(d) {\n        return divAndMod_BigInteger(this, d)[0];\n    }\n    function BigInteger_mod(d) {\n        return divAndMod_BigInteger(this, d)[1];\n    }\n\n    function BigInteger_log() {\n        var x = nativeToInexact(this.abs().log());\n        return this.isPositive() ? x : inexactRectangular(x, PI);\n    }\n\n    function BigInteger_exp10(e) {\n        switch (sign(e)) {\n        case 0:  return this;\n        case -1: return divide(this, exp10(ONE, negate(e)));\n        case 1:\n            e = +e;\n            if (e > SchemeNumber.maxIntegerDigits && !this.isZero())\n                integerTooBig(e);\n            return this.exp10(e);\n        }\n    }\n\n    function BigInteger_sqrt() {\n        var s = this.sign();\n        if (s === 0)\n            return this;\n        var mag = nativeToInexact(Math_exp(this.abs().log() / 2));\n        if (s < 0)\n            return inexactRectangular(INEXACT_ZERO, mag);\n        return mag;\n    }\n\n    function BigInteger_exactIntegerSqrt() {\n\n        // I know of no use cases for this.  Be stupid.  Be correct.\n\n        function doit(n, a) {\n            while (true) {\n                var dm = n.divRem(a);\n                var b = dm[0];\n                var diff = a.subtract(b);\n                // n == b*b + b*diff + dm[1], dm[1] < b+1\n\n                if (diff.isZero())\n                    return [ b, dm[1] ]; // n == b*b + dm[1]\n\n                if (diff.isUnit()) {\n                    if (diff.isPositive())\n                        // n == b*b + b + dm[1], dm[1] < b+1\n                        return [ b, b.add(dm[1]) ];\n\n                    // n == b*b - b + dm[1] == (b-1)^2 + b - 1 + dm[1]\n                    return [ a, a.add(dm[1]) ];\n                }\n\n                a = b.add(diff.quotient(2));\n            }\n        }\n\n        switch (this.sign()) {\n        case -1:\n            raise("&assertion", "negative number", this);\n        case 0:\n            return [ ZERO, ZERO ];\n        case 1: default:\n            break;\n        }\n        var l = this.log() / 2 / Math_LN10;\n\n        if (l < 7) {\n            // Use native arithmetic.\n            var x = this.valueOf();\n            var f = Math_floor(Math_sqrt(x));\n            return [BigInteger(f), BigInteger(x - f * f)];\n        }\n\n        var a = BigInteger(Number_toString(Math_pow(10, l - Math_floor(l)))\n                           + "e" + Math_floor(l));\n        return doit(this, a);\n    }\n\n    function BigInteger_gcdNonnegative(n) {\n        //assert(!isNegative(this));\n        //assert(!isNegative(n));\n\n        var a = this;\n        if (a.isZero())\n            return n;\n\n        var b = n;\n        var c;\n\n        while (true) {\n            c = a;\n            a = b.remainder(a);\n            if (a.isZero())\n                return c;\n        }\n    }\n\n    function makeBitOp(op) {\n        function BigInteger_bitwiseOp(b) {\n            var a = this;\n            var a = this;\n            //assert(!isNegative(a));\n            //assert(!isNegative(b));\n            var ret = BigInteger.ZERO;\n            var d = BigInteger.ONE;\n            var t, dm;\n            while (true) {\n                dm = a.divRem(_2_32);\n                t = +dm[1];\n                a = dm[0];\n                dm = b.divRem(_2_32);\n                t = op(t, +dm[1]);\n                b = dm[0];\n                if (t < 0)\n                    t += 0x100000000;\n                ret = ret.add(d.multiply(nativeToExactInteger(t)));\n                if (a.isZero())\n                    break;\n                d = d.multiply(_2_32);\n            }\n            if (op(0, 1))\n                ret = ret.add(b.multiply(d));\n            return ret;\n        }\n        return BigInteger_bitwiseOp;\n    }\n    var BigInteger_bitwiseIor = makeBitOp(function(x, y) { return x | y; });\n    var BigInteger_bitwiseXor = makeBitOp(function(x, y) { return x ^ y; });\n\n    function addOne(x) { return x + 1; }\n    var BIT_COUNT = [0];\n    while (BIT_COUNT.length < (1 << 8))\n        BIT_COUNT = Array_concat(BIT_COUNT, Array_map(BIT_COUNT, addOne));\n\n    function BigInteger_bitCount() {\n        //assert(!isNegative(this));\n        var a = this;\n        var ret = 0, dm, t;\n        while (!a.isZero()) {\n            dm = a.divRem(_2_32);\n            a = dm[0];\n            t = +dm[1];\n            ret += BIT_COUNT[(t >>  0) & 0xff];\n            ret += BIT_COUNT[(t >>  8) & 0xff];\n            ret += BIT_COUNT[(t >> 16) & 0xff];\n            ret += BIT_COUNT[(t >> 24) & 0xff];\n        }\n        return nativeToExactInteger(ret);\n    }\n    }\n\n    function BigInteger_bitLength() {\n        var a = this;\n        switch (a.sign()) {\n        case 0: return ZERO;\n        case -1: a = BigInteger.M_ONE.subtract(a);\n        }\n        var guess = a.log() / Math_LN2;\n        var test = Math_floor(guess);\n        // Could perhaps optimize through assumptions about accuracy.\n        // Could cache powers of 2.\n        var p2test = BigInteger.pow(2, Math_floor(guess));\n        if (p2test.compare(a) > 0) {\n            // too high!\n            while (true) {\n                a = a.add(a);\n                if (p2test.compare(a) <= 0)\n                    return nativeToExactInteger(test);\n                test--;\n            }\n        }\n        while (true) {\n            p2test = p2test.add(p2test);\n            test++;\n            if (p2test.compare(a) > 0)\n        }\n    }\n\n    var FFS = [1, 0];\n    while (FFS.length < (1 << 8)) {\n        FFS = FFS.concat(FFS);\n        FFS[0]++;\n    }\n\n    function BigInteger_firstBitSet() {\n        var a = this, dm, m, ret;\n        if (a.isZero())\n        if (a.isZero())\n            return MINUS_ONE;\n        for (ret = 0; ; ret += 32) {\n            dm = a.divRem(_2_32);\n            m = dm[1];\n            if (!m.isZero())\n                break;\n            a = dm[0];\n        }\n        m = +m;\n            ret += 8;\n            m >>= 8;\n        }\n        return nativeToExactInteger(ret + FFS[m & 0xff]);\n    }\n\n    function BigInteger_isBitSet(i) {\n        //assert(!isNegative(n));\n        var p2i = BigInteger.pow(2, +i);\n        return this.remainder(p2i.add(p2i)).compare(p2i) >= 0;\n    }\n    }\n\n    function BigInteger_copyBit(i, setIt) {\n        var p2i = BigInteger.pow(2, +i);\n        switch (setIt - isSet) {\n        case 0: return this;\n        case 1: return this.add(p2i);\n        case -1: default: return this.subtract(p2i);\n        }\n    }\n\n    function install() {\n        "use strict";\n        var disp                     = plugins.get("Dispatch");\n        var disp                     = plugins.get("Dispatch");\n        var ExactInteger             = plugins.get("ExactInteger");\n        var debug                    = plugins.get("debug");\n        var retThis                  = plugins.get("retThis");\n\n        disp.defClass("BigInteger", {ctor: BigInteger, base: "ExactInteger"});\n\n        // Have BigInteger rebuild its cache since its prototype changed.\n        BigInteger.init();\n\n        debug.def(BigInteger, BigInteger_debug);\n\n        toBigInteger.def(BigInteger, retThis);\n        toBigInteger.def(ExactInteger, ExactInteger_toBigInteger);\n\n        function def1(generic, func) {\n            plugins.get(generic).def(BigInteger, func);\n        }\n        function def2(generic, func) {\n            plugins.get(generic).def(BigInteger, BigInteger, func);\n        }\n        function defBigUnary(name) {\n            plugins.get(name).def(BigInteger, BigInteger.prototype[name]);\n        }\n        function defBigBinary(name) {\n            plugins.get(name).def(BigInteger, BigInteger,\n                                  BigInteger.prototype[name]);\n        }\n\n        def2("expt",           BigInteger_expt);\n        def1("numberToString", BigInteger_numberToString);\n\n        defBigUnary("isZero");\n        defBigUnary("isEven");\n        defBigUnary("isOdd");\n        defBigUnary("sign");\n        defBigUnary("isUnit");\n        defBigUnary("isPositive");\n        defBigUnary("isNegative");\n        defBigUnary("negate");\n        defBigUnary("abs");\n        defBigUnary("square");\n\n        defBigBinary("compare");\n        defBigBinary("add");\n        defBigBinary("subtract");\n        defBigBinary("multiply");\n\n        def1("log",        BigInteger_log);\n        def1("exp10",      BigInteger_exp10);\n        def1("sqrt",       BigInteger_sqrt);\n        def1("exactIntegerSqrt", BigInteger_exactIntegerSqrt);\n        def2("divAndMod",  BigInteger_divAndMod);\n        def2("div",        BigInteger_div);\n        def2("mod",        BigInteger_mod);\n        def2("gcdNonnegative", BigInteger_gcdNonnegative);\n\n        def2("bitwiseAnd", BigInteger_bitwiseAnd);\n        def2("bitwiseIor", BigInteger_bitwiseIor);\n        def2("bitwiseXor", BigInteger_bitwiseXor);\n        def1("bitCount",   BigInteger_bitCount);\n        def1("firstBitSet", BigInteger_firstBitSet);\n        def1("isBitSet",   BigInteger_isBitSet);\n        def1("copyBit",    BigInteger_copyBit);\n    }\n\n    api.parseExactInteger        = parseExactInteger;\n    api.parseExactInteger        = parseExactInteger;\n    api.nativeToExactInteger     = nativeToExactInteger;\n    api.importExactInteger       = toBigInteger;\n    api.install                  = install;\n    return api;\n}\n\n/*\n    Function: defaultRationalFactory(plugins)\n*/\nfunction defaultRationalFactory(plugins) {\n    "use strict";\n    var ExactRational            = plugins.get("ExactRational");\n    var g                        = plugins.get("es5globals");\n    var uncurry                  = plugins.get("uncurry");\n    var api = g.Object.create(null);\n\n    var Math_exp     = g.Math.exp;\n    var _isNaN       = g.isNaN;\n    var _isFinite    = g.isFinite;\n\n    var debug, retFalse, isUnit, numeratorAndDenominator, ZERO, ONE, TWO, makeRectangular, eq, compare, add, subtract, multiply, divide, negate, log, exp, isNegative, abs, sqrt, SN_isFinite, sign, div, expt, square, isZero, isPositive, isNegative, raiseDivisionByExactZero;\n\n    debug                    = plugins.get("debug");\n    retFalse                 = plugins.get("retFalse");\n    isUnit                   = plugins.get("isUnit");\n    numeratorAndDenominator  = plugins.get("numeratorAndDenominator");\n    ZERO                     = plugins.get("ZERO");\n    ONE                      = plugins.get("ONE");\n    TWO                      = plugins.get("TWO");\n    makeRectangular          = plugins.get("makeRectangular");\n    eq                       = plugins.get("eq");\n    compare                  = plugins.get("compare");\n    add                      = plugins.get("add");\n    subtract                 = plugins.get("subtract");\n    multiply                 = plugins.get("multiply");\n    divide                   = plugins.get("divide");\n    negate                   = plugins.get("negate");\n    log                      = plugins.get("log");\n    exp                      = plugins.get("exp");\n    isNegative               = plugins.get("isNegative");\n    abs                      = plugins.get("abs");\n    sqrt                     = plugins.get("sqrt");\n    SN_isFinite              = plugins.get("SN_isFinite");\n    sign                     = plugins.get("sign");\n    div                      = plugins.get("div");\n    expt                     = plugins.get("expt");\n    square                   = plugins.get("square");\n    isZero                   = plugins.get("isZero");\n    isPositive               = plugins.get("isPositive");\n    isNegative               = plugins.get("isNegative");\n    raiseDivisionByExactZero = plugins.get("raiseDivisionByExactZero");\n\n    // Fraction: Exact rational as numerator (exact integer) and\n    // denominator (exact integer greater than one) with no factors in\n    // common.\n\n    function Fraction(n, d) {\n        //assert(isInteger(n));assert(isExact(n));\n        //assert(isInteger(d));assert(isExact(d));\n        //assert(gt(d, ONE));\n        //assert(eq(ONE,gcdNonnegative(abs(n),d)));\n        //assert(this instanceof Fraction);\n        this._n = n;\n        this._d = d;\n    }\n    Fraction.prototype = new ExactRational();\n\n    function Fraction_debug() {\n        return "Fraction(" + debug(this._n) + " / " + debug(this._d) + ")";\n    }\n\n    // Convert exact rational to approximate native number.\n    function Fraction_valueOf() {\n        var n = this._n;\n        var d = this._d;\n        var ret = n / d;\n        if (_isFinite(ret))  // (-)Infinity / Infinity would give NaN.\n            return ret;\n\n        // Numerator or denominator fall outside the native range, but\n        // their quotient may lie within it.  Use logarithms.\n        switch (sign(n)) {\n        case 1:  return Math_exp(log(n) - log(d));\n        case -1: return -Math_exp(log(negate(n)) - log(d));\n        case 0: default:  return 0;\n        }\n    }\n\n    Fraction.prototype.valueOf = Fraction_valueOf;\n\n    function Fraction_numerator()   { return this._n; }\n    function Fraction_denominator() { return this._d; }\n\n    function divideReducedNotByOne(n, d) {\n        return new Fraction(n, d);\n    }\n    function _divideReduced(n, d) {\n        return (isUnit(d) ? n : new Fraction(n, d));\n    }\n\n    var importRational = plugins.get("Dispatch").defGeneric("toFraction", 1);\n\n    function Rational_toFraction() {\n        var nd = numeratorAndDenominator(this);\n        return _divideReduced(nd[0], nd[1]);\n    }\n\n    function Fraction_numeratorAndDenominator() {\n        return [this._n, this._d];\n    }\n\n    function Fraction_eq(q) {\n        return eq(this._d, q._d) &&\n            eq(this._n, q._n);\n    }\n\n    function Fraction_compare(q) {\n        var signDiff = sign(this._n) - sign(q._n);\n        if (signDiff !== 0)\n            return (signDiff > 0 ? 1 : -1);\n        if (q._d === this._d)  // cheap optimization, XXX could be eq(qd,td)\n            return compare(this._n, q._n);\n        return compare(multiply(this._n, q._d), multiply(this._d, q._n));\n    }\n    function Fraction_compare_Integer(n) {\n        return compare(this._n, multiply(this._d, n));\n    }\n    function Integer_compare_Fraction(q) {\n        return compare(multiply(this, q._d), q._n);\n    }\n\n    function Fraction_sign() {\n        return sign(this._n);\n    }\n    function Fraction_isPositive() {\n        return isPositive(this._n);\n    }\n    function Fraction_isNegative() {\n        return isNegative(this._n);\n    }\n    function Fraction_negate() {\n        return divideReducedNotByOne(negate(this._n), this._d);\n    }\n    function Fraction_square() {\n        return divideReducedNotByOne(square(this._n), square(this._d));\n    }\n    function Fraction_reciprocal() {\n        var n = this._n;\n        switch (sign(n)) {\n        case -1: return _divideReduced(negate(this._d), negate(n));\n        case 1: return _divideReduced(this._d, n);\n        case 0: default: raiseDivisionByExactZero();\n        }\n    }\n\n    function Fraction_add(q) {\n        return divide(add(multiply(this._n, q._d), multiply(q._n, this._d)),\n                      multiply(this._d, q._d));\n    }\n    function Fraction_add_Integer(n) {\n        return divideReducedNotByOne(\n            add(this._n, multiply(n, this._d)), this._d);\n    }\n    function Integer_add_Fraction(q) {\n        return divideReducedNotByOne(\n            add(multiply(this, q._d), q._n), q._d);\n    }\n\n    function Fraction_subtract(q) {\n        return divide(subtract(multiply(this._n, q._d),\n                               multiply(q._n, this._d)),\n                      multiply(this._d, q._d));\n    }\n    function Fraction_subtract_Integer(n) {\n        return divideReducedNotByOne(\n            subtract(this._n, multiply(n, this._d)), this._d);\n    }\n    function Integer_subtract_Fraction(q) {\n        return divideReducedNotByOne(\n            subtract(multiply(this, q._d), q._n), q._d);\n    }\n\n    function Fraction_multiply(q) {\n        return divide(multiply(this._n, q._n), multiply(this._d, q._d));\n    }\n    function times_int(n, d, i) {\n        var nd = numeratorAndDenominator(divide(i, d));\n        return _divideReduced(multiply(n, nd[0]), nd[1]);\n    }\n    function Fraction_multiply_Integer(i) {\n        return times_int(this._n, this._d, i);\n    }\n    function Integer_multiply_Fraction(q) {\n        return times_int(q._n, q._d, this);\n    }\n\n    function Fraction_divide(q) {\n        return divide(multiply(this._n, q._d), multiply(this._d, q._n));\n    }\n    function Fraction_divide_Integer(i) {\n        var nd = numeratorAndDenominator(divide(this._n, i));\n        return new Fraction(nd[0], multiply(nd[1], this._d));\n    }\n    function Integer_divide_Fraction(q) {\n        return divide(multiply(this, q._d), q._n);\n    }\n\n    function Fraction_expt_EI(p) {\n        var n, d;\n        switch (sign(p)) {\n        case 0: return ONE;\n        case 1:\n            n = this._n;\n            d = this._d;\n            break;\n        case -1: default:\n            n = this._d;\n            d = this._n;\n            p = abs(p);\n            if (isNegative(d)) {\n                n = negate(n);\n                d = negate(d);\n            }\n            if (isUnit(d))\n                return expt(n, p);\n        }\n        // Num and den are in lowest terms.\n        return divideReducedNotByOne(expt(n, p), expt(d, p));\n    }\n\n    function Fraction_sqrt() {\n        // This rational or its components may be too big for\n        // toInexact(), but its square root may not be.\n        var absN = abs(this._n);\n        var rootN = sqrt(absN), rootD = sqrt(this._d);\n        var ret;\n        if (SN_isFinite(rootN)) {\n            if (SN_isFinite(rootD))\n                ret = divide(rootN, rootD);\n            else\n                ret = exp(subtract(log(rootN), divide(log(this._d), TWO)));\n        }\n        else {\n            ret = exp(subtract(divide(log(absN), TWO),\n                               SN_isFinite(rootD) ? log(rootD)\n                                                  : divide(log(this._d), TWO)));\n        }\n        return (isNegative(this._n) ? makeRectangular(ZERO, ret) : ret);\n    }\n    function Fraction_log() {\n        return subtract(log(this._n), log(this._d));\n    }\n    function Fraction_floor() {\n        return div(this._n, this._d);\n    }\n\n    function install() {\n        var disp = plugins.get("Dispatch");\n        var EI   = plugins.get("ExactInteger");\n\n        disp.defClass("Fraction", {ctor: Fraction});\n\n        importRational.def(Fraction, plugins.get("retThis"));\n        importRational.def(ExactRational, Rational_toFraction);\n\n        function def(name, type1, type2, func) {\n            plugins.get(name).def(type1, type2, func);\n        }\n        function def1(name, func) {\n            plugins.get(name).def(Fraction, func);\n        }\n        function def2(name, func) {\n            plugins.get(name).def(Fraction, Fraction, func);\n        }\n\n        def1("debug",                   Fraction_debug);\n        def1("numerator",               Fraction_numerator);\n        def1("denominator",             Fraction_denominator);\n        def1("numeratorAndDenominator", Fraction_numeratorAndDenominator);\n        def1("isInteger",               retFalse);\n        def2("eq",                      Fraction_eq);\n        def("eq",         Fraction, EI, retFalse);\n        def("eq",         EI, Fraction, retFalse);\n        def2("compare",                 Fraction_compare);\n        def("compare",    Fraction, EI, Fraction_compare_Integer);\n        def("compare",    EI, Fraction, Integer_compare_Fraction);\n        def1("sign",                    Fraction_sign);\n        def1("isPositive",              Fraction_isPositive);\n        def1("isNegative",              Fraction_isNegative);\n        def1("isZero",                  retFalse);\n        def1("isUnit",                  retFalse);\n        def1("floor",                   Fraction_floor);\n        def1("negate",                  Fraction_negate);\n        def1("square",                  Fraction_square);\n        def1("reciprocal",              Fraction_reciprocal);\n        def2("add",                     Fraction_add);\n        def("add",        Fraction, EI, Fraction_add_Integer);\n        def("add",        EI, Fraction, Integer_add_Fraction);\n        def2("subtract",                Fraction_subtract);\n        def("subtract",   Fraction, EI, Fraction_subtract_Integer);\n        def("subtract",   EI, Fraction, Integer_subtract_Fraction);\n        def2("multiply",                Fraction_multiply);\n        def("multiply",   Fraction, EI, Fraction_multiply_Integer);\n        def("multiply",   EI, Fraction, Integer_multiply_Fraction);\n        def2("divide",                  Fraction_divide);\n        def("divide",     Fraction, EI, Fraction_divide_Integer);\n        def("divide",     EI, Fraction, Integer_divide_Fraction);\n        def("expt",       Fraction, EI, Fraction_expt_EI);\n        def1("sqrt",                    Fraction_sqrt);\n        def1("log",                     Fraction_log);\n    }\n\n    api.divideReducedNotByOne    = divideReducedNotByOne;\n    api.divideReduced            = _divideReduced;\n    api.importRational           = importRational;\n    api.install                  = install;\n    return api;\n}\n\n/*\n    Function: implementRectangular(plugins)\n*/\nfunction implementRectangular(plugins) {\n    "use strict";\n    var Real          = plugins.get("Real");\n    var Complex       = plugins.get("Complex");\n    var g             = plugins.get("es5globals");\n    var uncurry       = plugins.get("uncurry");\n    var api = g.Object.create(null);\n\n    var debug, isZero, isUnit, isPositive, isExact, isInexact;\n    var toInexact, negate, multiply, cos, sin;\n    var ZERO, ONE, MINUS_ONE, INEXACT_ZERO;\n\n    debug                    = plugins.get("debug");\n    isZero                   = plugins.get("isZero");\n    isUnit                   = plugins.get("isUnit");\n    isPositive               = plugins.get("isPositive");\n    isExact                  = plugins.get("isExact");\n    isInexact                = plugins.get("isInexact");\n    toInexact                = plugins.get("toInexact");\n    negate                   = plugins.get("negate");\n    multiply                 = plugins.get("multiply");\n    cos                      = plugins.get("cos");\n    sin                      = plugins.get("sin");\n\n    function onPluginsChanged(plugins) {\n        ZERO                     = plugins.get("ZERO");\n        ONE                      = plugins.get("ONE");\n        MINUS_ONE                = plugins.get("MINUS_ONE");\n        INEXACT_ZERO             = plugins.get("INEXACT_ZERO");\n    }\n    plugins.onChange.subscribe(onPluginsChanged);\n    onPluginsChanged(plugins);\n\n    function Rectangular(x, y) {\n        //assert(this instanceof Rectangular);\n        //assert(isReal(x));\n        //assert(isReal(y));\n        //assert(isExact(x) === isExact(y));\n        //assert(!isExact(x) || !isZero(x));\n        this._x = x;\n        this._y = y;\n    }\n    Rectangular.prototype = new Complex();\n\n    function Rectangular_realPart() { return this._x; }\n    function Rectangular_imagPart() { return this._y; }\n\n    function Rectangular_conjugate() {\n        if (isExact(this._x))\n            return exactRectangular(this._x, negate(this._y));\n        return inexactRectangular(this._x, negate(this._y));\n    }\n\n    function Rectangular_debug() {\n        return "Rectangular(" + debug(this._x) + ", " + debug(this._y) + ")";\n    }\n\n    var I        = new Rectangular(ZERO, ONE);\n    var MINUS_I  = new Rectangular(ZERO, MINUS_ONE);\n\n    /*\n        Function: exactRectangular(x, y)\n        This function behaves like the standard <make-rectangular> but\n        assumes both arguments are exact reals.\n     */\n    function exactRectangular(x, y) {\n        //assert(isExact(x));\n        //assert(isExact(y));\n        if (isZero(y))\n            return x;\n        if (isZero(x) && isUnit(y)) {\n            return isPositive(y) ? I : MINUS_I;\n        }\n        return new Rectangular(x, y);\n    }\n\n    /*\n        Function: inexactRectangular(x, y)\n        This function behaves like the standard <make-rectangular> but\n        assumes both arguments are inexact reals.\n     */\n    function inexactRectangular(x, y) {\n        //assert(!isExact(x));\n        //assert(!isExact(y));\n        return new Rectangular(x, y);\n    }\n\n    /*\n        Function: inexactPolar(r, theta)\n        This function behaves like the standard <make-polar> but assumes\n        both its arguments are inexact and real.\n    */\n    function inexactPolar(r, theta) {\n        return inexactRectangular(\n            multiply(cos(theta), r), multiply(sin(theta), r));\n    }\n\n    /*\n        Function: exactPolar(r, theta)\n        This function behaves like the standard <make-polar> but assumes\n        both its arguments are exact and real.\n    */\n    function exactPolar(r, theta) {\n        // XXX Everybody seems to return inexact here, but I don\'t\n        // think it\'s allowed in cases like "#e1@1".\n        return inexactPolar(toInexact(r), toInexact(theta));\n    }\n\n    function Rectangular_isExact()   { return isExact(this._x); }\n    function Rectangular_isInexact() { return isInexact(this._x); }\n\n    api.Rectangular               = Rectangular;\n    api.Rectangular_debug         = Rectangular_debug;\n    api.Rectangular_realPart      = Rectangular_realPart;\n    api.Rectangular_imagPart      = Rectangular_imagPart;\n    api.Rectangular_conjugate     = Rectangular_conjugate;\n    api.exactRectangular          = exactRectangular;\n    api.inexactRectangular        = inexactRectangular;\n    api.exactPolar                = exactPolar;\n    api.inexactPolar              = inexactPolar;\n    api.Rectangular_isExact       = Rectangular_isExact;\n    api.Rectangular_isInexact     = Rectangular_isInexact;\n    return api;\n}\n\nfunction installRectangular(plugins) {\n    var Rectangular = plugins.get("Rectangular");\n\n    function def(generic, impl) {\n        var func = plugins.get(impl);\n        if (!func) {\n            console.log(impl + " is not defined");\n        }\n        plugins.get(generic).def(Rectangular, func);\n    }\n\n    def("isReal",     "retFalse");\n    def("isRational", "retFalse");\n    def("isInteger",  "retFalse");\n\n    function defRect(name) {\n        def(name, "Rectangular_" + name);\n    }\n\n    defRect("realPart");\n    defRect("imagPart");\n    defRect("isExact");\n    defRect("isInexact");\n    defRect("conjugate");\n}\n\nfunction defaultIntegerFactory(plugins) {\n    // Grab the BigInteger library.\n    // XXX should avoid use of globals.\n    var BigInteger;\n    if (typeof require !== "undefined")\n        BigInteger = require("./biginteger").BigInteger;\n    else\n        BigInteger = this.BigInteger;\n\n    if (!BigInteger) {\n        if (typeof load !== "undefined")\n            load("biginteger.js");\n        else if (this.readFile)\n            eval(this.readFile("biginteger.js"));\n        else\n            throw new Error("BigInteger is not defined.");\n    }\n    return implementBigInteger(plugins, BigInteger);\n}\n\nfunction configure(conf) {\n\n    // Build the SchemeNumber object piece by piece.\n\n    // XXX should probably provide a unique DispatchJs prefix.\n    var SchemeNumber = makeBase();\n    var plugins      = SchemeNumber.plugins;\n    var disp         = plugins.get("Dispatch");\n    var debug        = plugins.get("debug") || {def: function(){}};\n\n    var integerFactory  = conf.integerFactory  || defaultIntegerFactory;\n    var rationalFactory = conf.rationalFactory || defaultRationalFactory;\n    //integerFactory = require(\'./lib/leemonBigInt\').leemonBigIntFactory;\n\n    var Integers = integerFactory(plugins);\n    Integers.install();\n    plugins.extend(\n        "nativeToExactInteger", Integers.nativeToExactInteger,\n        "parseExactInteger",    Integers.parseExactInteger\n    );\n    installDefaultExactInteger(plugins, Integers.importExactInteger);\n\n    var Rationals = rationalFactory(plugins);\n    Rationals.install();\n    plugins.extend(\n        "divideReducedNotByOne", Rationals.divideReducedNotByOne\n    );\n    installDefaultRational(plugins, Rationals.importRational,\n                           Rationals.divideReduced);\n\n    // XXX This could use some refactoring.\n\n    var Rectangulars = implementRectangular(plugins);\n    var Rectangular = Rectangulars.Rectangular;\n    plugins.extend(Rectangulars);\n    disp.defClass("Rectangular", {ctor: Rectangular});\n    debug.def(Rectangular, Rectangulars.Rectangular_debug);\n    installRectangular(plugins);\n\n    var Flonums = implementNativeInexactReal(plugins);\n    var Flonum = Flonums.NativeInexactReal;\n    plugins.extend("Flonum", Flonum);\n    plugins.extend(Flonums);\n    plugins.extend(implementNativeFlonumLibrary(plugins));\n    disp.defClass("NativeInexactReal", {ctor: Flonum});\n    debug.def(Flonum, Flonums.NativeInexactReal_debug);\n    installFlonum(plugins);\n\n    // XXX TO DO\n\n    return SchemeNumber;\n}\n\nvar SchemeNumber = configure({});\nSchemeNumber.configure = configure;\nreturn SchemeNumber;\n})();\n\nif (typeof exports !== "undefined") {\n    exports.SchemeNumber = SchemeNumber;\n}\n\n// load for testing:\n// var sn=require("./schemeNumber").SchemeNumber;fn=sn.fn;ns=fn["number->string"];debug=sn.plugins.get("debug");1\n// load("biginteger.js");load("schemeNumber.js");sn=SchemeNumber;fn=sn.fn;ns=fn["number->string"];debug=sn.plugins.get("debug");1\n', 'message': 'Bitwise operations for BigInteger.\n', 'author_name': 'John Tobey', 'lang': 'js'}