Skip to content

Instantly share code, notes, and snippets.

@puffnfresh
Created October 4, 2012 04:40
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save puffnfresh/3831514 to your computer and use it in GitHub Desktop.
Save puffnfresh/3831514 to your computer and use it in GitHub Desktop.
do-notation using sweet.js
macro $do {
case { $y:expr } => {
$y
}
case { $x:ident <- $y:expr $rest ... } => {
λ['>=']($y, function($x) {
return $do { $rest ... }
});
}
}
// Using the bilby.js functional programming library:
// https://github.com/pufuwozu/bilby.js
var λ = require('./bilby');
// Haskell:
//
// do
// x <- [1, 2]
// y <- [x, x]
// [y * 2, y * 3]
//
// [2,3,2,3,4,6,4,6]
// sweet.js:
// Can't use arrays directly because of https://github.com/mozilla/sweet.js/issues/28
// Need to manually replace a, b and c in output with array expressions.
var list = $do {
x <- a // [1, 2]
y <- b // [x, x]
c // [y * 2, y * 3]
};
console.log(list);
// [ 2, 3, 2, 3, 4, 6, 4, 6 ]
@pbouzakis
Copy link

This is awesome! Nice job

@XertroV
Copy link

XertroV commented Jan 21, 2020

Note: the "can't use arrays directly" bit isn't an issue anymore apparently: sweet-js/sweet-core#28
For anyone coming here in the future you might want to check out: https://github.com/fantasyland/sweet-fantasies/blob/master/src/do.sjs

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