Generating Church Encoded Numbers for Arbitrary Integers in Javascript [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want a function that takes an integer and returns that number in the form of a church encoded function.
I have achieved this in newlisp:
(define (reduce stencil sq) (apply stencil sq 2))
(define (num n) (cond
((= n 0) 'x)
((< n 2) '(f x))
(true (reduce (fn (l i) (list 'f l)) (cons '(f x) (sequence 2 n)) ))))
(define (church-encode n)
(letex ((body (num n)))
(fn (f x) body)))
If I call (church-encode 0) I get back a lambda of the church-encoded zero:
(lambda (f x) x)
And (church-encode 3) will yield:
(lambda (f x) (f (f (f x))))
But I want to do the same in Javascript. Preferably without resorting to string jank like I have done here:
(function (_) {
var asnum = function(x) { return x((function(x) {return x+1;}), 0); };
function church_encode(n) {
function genBody() {
return _.reduce(_.range(n), function(e,x) {
return e.replace("x", "f(x)");
}, "x");
}
eval("var crap = function (f, x) { return "+genBody()+"; }");
return crap;
}
var encoded_nums = _.map(_.range(11), church_encode);
var numerics = _.map(encoded_nums, asnum);
console.log(numerics);
})(require('lodash'));

(function () {
function range(n){
var l = [];
for(var i = 0; i < n; i++){
l.push(i);
}
return l;
}
function church_encode(n) {
if(n < 1)
return function(f, x) { return x; };
if(n === 1)
return function(f, x) { return f(x); };
function succ (n) {
return function(f,x) {
return n(f,f(x));
}
}
return range(n).reduce(function(a){
return succ(a);
}, function (f,x) { return x; });
}
function to_int(f){
var i = 0;
f(function(){ i++ });
return i;
};
console.log(to_int(church_encode(5)));
})();

Related

Sum of Digits / Digital Root codewars kata [duplicate]

This question already has answers here:
Recursive function returns undefined
(3 answers)
Closed 1 year ago.
Please, help me. I don't understand. Why second solution returns undefined?
function digital_root(n) {
return n < 10 ? n : digital_root(n.toString().split('').map(Number).reduce((a, b) => a + b));
}
console.log(digital_root(12345678));
// expected output: 9
function digital_root(n) {
if (n < 10) {
return n;
} else {
digital_root(n.toString().split('').map(Number).reduce((a, b) => a + b));
}
}
console.log(digital_root(12345678));
// output: undefined
This happens because your second code ignores the value you get returned from the recursive call. You should do something with it... return it.
function digital_root(n) {
if (n < 10) {
return n;
} else {
return digital_root(n.toString().split('').map(Number).reduce((a, b) => a + b));
}
}
console.log(digital_root(12345678));
Unrelated, but you can combine split and map by doing Array.from. Also the first version joins the two return statements with the conditional operator into a return of one expression:
const digital_root = n => n < 10 ? n
: digital_root(Array.from(n.toString(), Number).reduce((a, b) => a + b));
console.log(digital_root(12345678));

Trying to make a repeater function using only higher order functions?

I'm trying to make a function that accepts another function and outputs that function repeatedly by only using function expressions/applications.
So far I have a function twice which accepts another function as an argument and returns func(func(x)):
function twice(func) {
function x(x) {
return func(func(x));
}
return x;
}
I'm trying to make a repeater function such that const thrice = repeater(twice) returns func(func(func(x))), and const fourtimes = repeater(thrice) etc. but i'm confused as to how to do this. Any help would be appreciated greatly. Thank you
Using your current structure thats impossible as twice does not expose a reference to func, thus repeater cannot call it.
The only solution I could think of would be to leak func from the inside through a (hidden) property:
const r = Symbol();
const repeater = f => Object.assign(
v => f[r] ? f(f[r](v)): f(v),
{ [r]: f[r] || f }
);
const addThree = repeater(repeater(repeater(n => n + 1)));
console.log(addThree(10));
You should two base cases (if n == 0 => exit, if n == 1 => return f(x)), where n is an additional parameter that specifies how many times the function should repeat with the arguments args:
function repeater(func, x, n) {
if (n == 0) return;
if (n == 1) return func(x);
else {
return func(repeater(func, x, --n));
}
}
let sqr = n => n * n;
console.log(repeater(sqr, 2, 3));
Do you look for something like this?
function chain(f, g) {
return function (x) {
return f(g(x));
}
}
function ntimes(f, n) {
if (n == 0) {
return function (x) { return x }
} else {
return chain(f, ntimes(f, n-1));
}
}
This will make a new function which repeats the original function f n times.

Number Formatting for large integer numbers in Javascript

I know there are in-build function in javascript like toLocalString() to achieve number formatting. But this question is purely for learning and logic understanding.
I have a function in javascript that formats given number in Indian Number formatting standards (eg: 1,234 | 12,21,123 | etc)
Code
function formatter(input) {
var inputStr = input.toString(), l = inputStr.length;
var c = 1, f = 0;
console.log(l);
for (var x=l-1; x>=0; x--) {
if (x === 0) {
continue;
}
if (c === 3 && f === 0) {
inputStr = inputStr.substring(0, x) + ',' + inputStr.substring(x);
f = 1;
c = 0;
} else if (c % 2 === 0 && f === 1) {
inputStr = inputStr.substring(0, x) + ',' + inputStr.substring(x);
c = 0;
}
c++;
}
return inputStr;
}
Now this works for most part (as far as I have test, do point out bugs if you spot any). But my question is how do I handle large number in this, i.e. how do I handle values greater than 9007199254740991.
Hope this now fixes the issue:
function formatter(inputStr) {
inputStr+="";
let c = 1, f = 0;
for (let x=inputStr.length-1; x>=0; x--) {
if (x === 0) continue;
if (c === 3 && f === 0) {
inputStr = inputStr.substring(0, x) + ',' + inputStr.substring(x);
f = 1;
c = 0;
} else if (c % 2 === 0 && f === 1) {
inputStr = inputStr.substring(0, x) + ',' + inputStr.substring(x);
c = 0;
}
c++;
}
return inputStr;
}
//========= Tests =======
console.log(formatter(9007199254740991));
console.log(formatter("900719925474093454549341"));
console.log(formatter("123456678890987665443221112345667676766545434243"));

javascript + mocha: probably a closure issue with functions declared inside a for loop

To learn javascript, I implement and test classic algorithms with it.
Here is my attempt at implementing binary search and tests for it:
var assert = require('assert')
function binsearch (xs, v) {
if (xs === undefined || xs.length === 0) { return null }
var lo = 0
var hi = xs.length - 1
while (lo <= hi) {
var i = (lo + hi) / 2 | 0
if (xs[i] === v) {
return i
} else if (v < xs[i]) {
hi = i - 1
} else if (v > xs[i]) {
lo = i + 1
}
}
return null
}
var check_bsearch = function (bsearch, xs, x, i) {
it(bsearch.name + ' [' + xs + '] ' + x + ' ' + i, function () {
assert.equal(bsearch(xs, x), i)
})
}
describe('Test binsearch', function () {
describe('on a sorted array', function() {
var xs = []
for (var i = 0; i < 2; ++i) {
xs[i] = 2 * i
for (var j = 0; j <= i; ++j) {
check_bsearch(binsearch, xs, 2 * j, j)
check_bsearch(binsearch, xs, 2 * j + 1, null)
check_bsearch(binsearch, xs, -1, null)
check_bsearch(binsearch, xs, -2, null)
check_bsearch(binsearch, xs, 2 * i + 1, null)
check_bsearch(binsearch, xs, 2 * i + 2, null)
}
}
})
})
In order to reproduce what I am about to say, copy the code above into some bsearch.js file, install mocha.js with something like sudo npm install -g mocha and finally run the file: mocha bsearch.js
One test should be failing: the one with xs = [0], x = 2 and expected result of null. If you recreate this test separately though, it will pass.
I am suspecting that this is a closure issue. You might have noticed that I am already using a helper function check_bsearch to get the expected closure environment. However, I am clearly missing something. How do I fix the tests?
Arrays are passed by reference. What happens is that as you loop you modify the xs array you pass to your functions, and by the time the tests actually run, they all get the same value. You should copy the array so that each test gets a snapshot of its value at the time it was called. It can be as simple as:
var check_bsearch = function (bsearch, xs, x, i) {
xs = xs.slice(); // Make a private copy of xs.

visual studio vs filezilla for publishing website [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
My first Question:Which is better publish a web site from visual studio,or upload it by filezilla?
I didn't try any of them but someone told me when using filezilla:when I try to access my website, i get a file listing and when i try to view one of them, i just get a html text version of my pages.
but then again he said filezilla keeps the website even if it goes offline,is visual studio also the same?
And my SECOND Questin:
This is a jquery or javascript function?am I right?(which one?)
I saw it in a source code of a site,why does it look strange?I can't understand it,it has been encrypted?how can I turn it to sth which is more understandable?
(function (a, b) {
function c(a) { return K.isWindow(a) ? a : a.nodeType === 9 ? a.defaultView || a.parentWindow : !1 } function d(a) { if (!cl[a]) { var b = H.body, c = K("<" + a + ">").appendTo(b), d = c.css("display"); c.remove(); if (d === "none" || d === "") { cm || (cm = H.createElement("iframe"), cm.frameBorder = cm.width = cm.height = 0), b.appendChild(cm); if (!cn || !cm.createElement) cn = (cm.contentWindow || cm.contentDocument).document, cn.write((H.compatMode === "CSS1Compat" ? "<!doctype html>" : "") + "<html><body>"), cn.close(); c = cn.createElement(a), cn.body.appendChild(c), d = K.css(c, "display"), b.removeChild(cm) } cl[a] = d } return cl[a] } function e(a, b) { var c = {}; return K.each(cr.concat.apply([], cr.slice(0, b)), function () { c[this] = a }), c } function f() { cs = b } function g() { return setTimeout(f, 0), cs = K.now() } function h() { try { return new a.ActiveXObject("Microsoft.XMLHTTP") } catch (b) { } } function i() { try { return new a.XMLHttpRequest } catch (b) { } } function j(a, c) { a.dataFilter && (c = a.dataFilter(c, a.dataType)); var d = a.dataTypes, e = {}, f, g, h = d.length, i, j = d[0], k, l, m, n, o; for (f = 1; f < h; f++) { if (f === 1) for (g in a.converters) typeof g == "string" && (e[g.toLowerCase()] = a.converters[g]); k = j, j = d[f]; if (j === "*") j = k; else if (k !== "*" && k !== j) { l = k + " " + j, m = e[l] || e["* " + j]; if (!m) { o = b; for (n in e) { i = n.split(" "); if (i[0] === k || i[0] === "*") { o = e[i[1] + " " + j]; if (o) { n = e[n], n === !0 ? m = o : o === !0 && (m = n); break } } } } !m && !o && K.error("No conversion from " + l.replace(" ", " to ")), m !== !0 && (c = m ? m(c) : o(n(c))) } } return c } ...
it countinues
Your friend told you non-sense or you understood it that way. There's more than plain file transfer in VS deploy solution (like compilation of your source code into a dll for example), that can be fine tuned and so. Filezilla on its side is just plain ftp : you send the files you wish to a server.
You're not supposed to ask 2 questions at the same time, but still, to your second question :
this looks a lot like javascript, and it probably was minimized. This is a technique in which a parser replaces variable names by short names (letters), removes whitespaces and line feeds, etc in order to make the file smaller. Oh and JQuery is actually a javascript framework so there's no big difference between both.

Categories