Last active
August 29, 2015 14:00
-
-
Save barretron/11396531 to your computer and use it in GitHub Desktop.
Possible CS Generator Syntax
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| koa = require 'koa' | |
| app = koa() | |
| generator firstn | |
| initialize: (limit) -> | |
| num = 0 | |
| while num < limit | |
| yield num | |
| num += 1 | |
| generator repeat | |
| initialize: (num) -> | |
| loop | |
| yield num | |
| generator koa_res | |
| initialize: -> | |
| this.body = "Hello World!" | |
| app.use koa_res | |
| # use `new` keyword so that CS can check | |
| # to make sure people are using generators correctly | |
| # (you have to initialize them first) | |
| x = new (firstn 1000) | |
| # these functions are all part of the ES6 spec | |
| x.next() | |
| x.send(5) | |
| x.throw() | |
| x.close() | |
| x.iterate() | |
| # ---------------- | |
| // Proposed compilation | |
| var koa, app, firstn, repeat, koa_res, x; | |
| koa = require("koa"); | |
| app = koa(); | |
| firstn = function*(limit) { | |
| var num; | |
| num = 0; | |
| while(num < limit) { | |
| yield num; | |
| num += 1; | |
| } | |
| }; | |
| repeat = function*(num) { | |
| while(true) { | |
| yield num; | |
| } | |
| }; | |
| koa_res = function*() { | |
| this.body = "Hello World!"; | |
| }; | |
| app.use(koa_res); | |
| x = firstn(1000); | |
| x.next(); | |
| x.send(5); | |
| x.throw(); | |
| x.close(); | |
| x.iterate(); | |
| ------- | |
| PROS: | |
| + consistent with CS class layout | |
| + allows CS to check for proper generator usage (initialization, etc.) | |
| + more beginner friendly (you can't make a generator unless you really know what you're doing) | |
| + allows CS to hide generator internals | |
| + similar to JS by defining generator in function signature | |
| + way easier for parser to figure out return values (possibly extend Class in lexer). | |
| + you can have empty generators if you really want them (analogous to `fn = ->` for a regular function, which compiles to `var fn; fn = function() {};` ) | |
| CONS: | |
| + more verbose than auto-detection | |
| + generator isn't currently reserved (the structure prevents confusion, though). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment