Skip to content

Instantly share code, notes, and snippets.

@svanellewee
Last active August 29, 2015 14:14
Show Gist options
  • Select an option

  • Save svanellewee/fb3391cec5bcc47404a8 to your computer and use it in GitHub Desktop.

Select an option

Save svanellewee/fb3391cec5bcc47404a8 to your computer and use it in GitHub Desktop.
Javascript + Church + Mcarthy
/*
according to Church you can represent a datastructure by means of a function like so:
\x\a\b.x(a,b) where a and b are given constants and x is a function to be provided later...
*/
function cons(head, tail) {
return function (e) {
return e(head, tail);
}
}
/*
that means you can use the following to determine the head of this "datastructure"
*/
function car(cns) {
return cns(function (a, b) {
return a;
})
}
/*
also, the tail is similarly attainable
*/
function cdr(cns) {
return cns(function (a, b) {
return b;
})
}
/*
forEach redone:
*/
function iterate(cns, fn) {
return cns(function (head, tail) {
fn(head)
if (tail !== null) {
return iterate(tail, fn)
}
})
}
/*
fold right/ reduceRight
*/
function foldr(cns, fn, initial) {
return cns(function (head, tail) {
newval = fn(head, initial)
if (tail !== null && tail !== undefined) {
return foldr(tail, fn, newval)
}
return newval
})
}
/*
fold left/ reduce.. here I cheated, decided to describe in terms of foldRight
*/
function foldl(cns, fn, initial){
var revcons = foldr(cns,cons, null)
return foldr(revcons, fn, initial)
}
/*
Example usage
*/
var alist = cons(1, cons(2, null))
var blist = cons(1, cons(2, cons(33, null)))
console.log(car(alist))
console.log(car(cdr(alist)))
var printnode = function (a) {
console.log('>>', a)
}
iterate(alist, printnode)
iterate(blist, printnode)
console.log(foldl(blist, function (head, ini) {
console.log('..!', head, ini);
return head + ini
}, 0))
var xlist = foldl(blist, function (head, ini) {
return cons(head, ini);
}, null)
iterate(xlist, printnode)
foldr(blist,function(head, ini){
return "(+ "+head+" "+ini+")"
},0)
/*
(+ 33 (+ 2 (+ 1 0)))
*/
foldl(blist,function(head, ini){
return "(+ "+head+" "+ini+")"
},0)
/*
(+ 1 (+ 2 (+ 33 0)))
*/
@svanellewee
Copy link
Author

According to wikipedia fold/reduce is a way of replacing the cons function in the list with another function, for example

cons(1, cons(2, cons(30, null))) 

replace _cons_ with _add_ (initial value 10):

add(1, add(2, add(30, 10)))

@svanellewee
Copy link
Author

While reading up on Church's Lambda calculus I was unable to figure out how one would use this to base a programming language on this. It turns out that you can describe data structures in terms of functions too though!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment