Scheme in about 10 lines of Javascript
A use of your limited time
What is Scheme?
A functional languange with a minimal core. It relies on first-class functions to implement lists, and recursion for iteration.
We can implement the most salient features of Scheme in about 10 lines of Javascript.
Why? Because it's there.
What we need
- A function for creating a pair.
- A function for getting the first part of the pair.
- A function for getting the second part of the pair.
- That's enough to build virtually everything else.
Creating a pair
function pair(x, y) {
return function(f) { return f(x, y); };
}
Getting the first part
function head(f) {
return f(function(x, y) { return x; });
}
Getting the second part
function tail(f) {
return f(function(x, y) { return y; });
}
Scheme in about 10 lines of Javascript
function pair(x, y) {
return function(f) { return f(x, y); };
}
function head(f) {
return f(function(x, y) { return x; });
}
function tail(f) {
return f(function(x, y) { return y; });
}
// and this line is a comment
It works
console.log(head(pair(1, 2)));
console.log(tail(pair(1, 2)));
... but what is it?
console.log(typeof pair(1, 2));
Taking it further
What if we nest pairs?
console.log(typeof pair(1, pair(2, pair(3, null))));
We've got a list, and we can get at its elements using head
and tail
List
We can use some native Javascript to implement the list
function:
function list() {
var args = Array.prototype.slice.call(arguments);
return (args.length === 0) ? null :
pair(args.shift(), list.apply(null, args));
}
console.log(head(tail(tail(list(1, 2, 3, 4, 5, 10)))));
←
→
/
#