Files
nothing/nothing-helper.js
2018-06-04 21:02:05 +02:00

54 lines
1.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const nothing = require('./nothing.js');
const charset = '0123456789BFiuz';
const from_int = (n) => {
let f = nothing.ZERO;
for (let _ = 0; _ < n; _++) f = nothing.INC(f);
return f;
};
const to_int = (f) => nothing.TIMES(f)(i => i+1)(0);
const from_bool = (b) => b ? nothing.TRUE : nothing.FALSE;
const to_bool = (f) => f(true)(false);
const to_array = (l) => {
let a = [];
while (!to_bool(nothing.IS_EMPTY(l))) {
a.push(nothing.FIRST(l));
l = nothing.REST(l);
}
return a;
};
const from_array = (a) => {
let l = nothing.EMPTY;
while (a.length) l = nothing.UNSHIFT(l)(a.pop());
return l;
};
const to_char = (c) => charset[to_int(c)];
const from_char = (c) => from_int(charset.indexOf(c));
const to_string = (s) => to_array(s).map(to_char).join('');
const from_string = (s) => from_array(s.split('').map(from_char));
const representation_of = (v) => {
if (typeof v == "number") return from_int(v);
if (typeof v == "boolean") return from_bool(v);
if (typeof v == "string") return from_string(v);
if (Array.isArray(v)) return from_array(v.map(representation_of));
throw Error(`Oops, I dont know how represent this: ${v}`);
};
const zip = (a, b) => a.map((e, i) => [e, b[i]]);
const check_represent = function(r, v) {
if (typeof v == "number") return to_int(r) == v;
if (typeof v == "boolean") return to_bool(r) == v;
if (typeof v == "string") return to_string(r) == v;
if (Array.isArray(v)) {
let a = to_array(r);
return a.length == v.length && zip(a, v).every(([r, v]) => check_represent(r,v));
}
throw Error(`Oops, I dont know how check this: ${v}`);
};
module.exports = {
representation_of, check_represent
};