This post is a continuation of my previous post, Capturing abstractions in Lisp.
Today I was playing with Sweet.JS, a JavaScript library that adds the possibility to make macros within the language.
I went through the tutorial and it is pretty straight-forward.
// delay needs to be a macro in order for the code to work correctly.
// Otherwise the invocation of delay will evaluate all its arguments eagerly.
syntax delay = function (ctx) {
let x = ctx.next().value;
return #`(function() { return ${x} })`;
}
// similarly for cons-stream
syntax cons_stream = function(ctx) {
const [...args] = ctx.next().value.inner();
let param1 = args[0];
let param2 = args.slice(2);
return #`([${param1}].concat(delay(${param2})))`;
}
// force just evaluates
function force(x) {
return x();
}
function next_integer(x) {
return cons_stream(x, next_integer(x+1));
}
function all_positive_integers() {
return next_integer(0);
}
function integer_ref(list, j) {
if (j == 0) {
return list[0];
} else {
return integer_ref(force(list[1]), j - 1);
}
}
var integers = all_positive_integers();
// display 100th number:
console.log(integer_ref(integers, 100));
With this code snippet, we can see that using this library we get a very powerful Lisp-like syntax 🙂