Skip to content

Instantly share code, notes, and snippets.

@int3
Created November 6, 2012 21:17
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save int3/4027626 to your computer and use it in GitHub Desktop.
Save int3/4027626 to your computer and use it in GitHub Desktop.
Chained comparisons using sweet.js
macro $if {
case ($x ...) => { if (relCar($x ...)) }
}
macro $while {
case ($x ...) => { while (relCar($x ...)) }
}
// naive form:
/*
macro rel {
case $x => { $x }
case ($x:ident $op $y:ident $rest ...) => {
$x $op $y && $rel($y $rest ...)
}
}
*/
// better: works even with the presence of &&, |, etc.
macro relGen {
case ($cmp ...) => {
macro relCar {
$(case ($x $cmp $y $rest $[...]) => {
$x $cmp $y relCdr($y $rest $[...])
}) ...
case $x => { $x }
}
macro relCdr {
$(case ($y $cmp $z) => {
&& $y $cmp $z
}) ...
/* since the following two sequences are of equal length, order is important */
case ($y:ident $op $z:ident $rest $[...]) => {
$op relCar($z $rest $[...])
}
$(case ($y:ident $cmp $z:ident $rest $[...]) => {
&& $y $cmp $z relCdr($z $rest $[...])
}) ...
case $y => { $y }
}
}
}
relGen(>= <= > < != !== === ==)
$while (1 > 2 > 3 >= 4 <= 5 > 6) {
console.log("foo");
}
$if (1 < 2 < 3 < 4 < 5 < 6) {
console.log("bar");
}
$if (1 < 2 && 3 < 4 < 5 || 1 == 2 == 3) {
console.log("bar");
}
// result:
/*
while (1 > 2 && 2 > 3 && 3 >= 4 && 4 <= 5 && 5 > 6) {
console.log('foo');
}
if (1 < 2 && 2 < 3 && 3 < 4 && 4 < 5 && 5 < 6) {
console.log('bar');
}
if (1 < 2 && 3 < 4 && 4 < 5 || 1 == 2 && 2 == 3) {
console.log('bar');
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment