5 ms·
Python Internals: Adding a new statement to Python
- brlewis 16y agoThe Scheme version is not worthy of a blog post: (define-syntax until (syntax-rules () ((until pred expr ...) (let loop () (if (not pred) (begin (begin expr ...) (loop))))))) In dialects with WHEN syntax (mzcheme, Kawa, probably many others) it's even more concise: (define-syntax until (syntax-rules () ((until pred expr ...) (let loop () (when (not pred) (begin expr ...) (loop))))))
- CWuestefeld 16y agoI will never, ever do this. But I still love this kind of article, that gives a deeper insight into how things work.
- Goladus 16y agoIf you've never messed with real parsing and compiling before I highly recommend it. It's like lifting programmer weights, so many other problems seem easy afterwards.
- CWuestefeld 16y agoYes, I took compiler design in college, and even in the real world I've had lex and yacc coming out my ears. But specifically, I'm never going to add new statements to the python interpreter.
- dlo 16y agoIf you like working on the compiler front-end, wait 'til you take a look at what happens in the back-end. Phenomenal.
- zephjc 16y ago"There should be one-- and preferably only one --obvious way to do it." 'while' is it, 'until' is not. The author even notes that 'until cond' is functionally identical to 'while not condition'. A fun exercise for the author, if a bit silly.
- deleted 16y ago[deleted]
- brlewis 16y agoFrom the section "A language-advocacy digression": This article doesn’t attempt to suggest the addition of an until statement to Python. Although I think such a statement would make some code clearer, and this article displays how easy it is to add, I completely respect Python’s philosophy of minimalism. All I’m trying to do here, really, is gain some insight into the inner workings of Python.
- jcsalterego 16y agoGreat breakdown. I tried something simpler once, trying to map str.format() to a binary operator in Py3k. http://github.com/jcsalterego/py3k-atsign http://github.com/jcsalterego/py3k-atsign Needless to say it didn't pass the python-ideas (or was that python-dev?) mailing list trial, mostly because it produced ambiguities that plagued the % operator, which prompted this new str method in the first place.
- draegtun 16y agoGeneral observation about until. I think it works better "linguistically" as a REPEAT/UNTIL (ala BASIC) and not as a negative while loop. So block of code always gets run at least once. For eg. in Perl: my $x; do { print "guess the number? "; $x = readline; } until $x == 10; Disclaimer: Can't recall using until since I last played with BASIC. And that was many years ago :)
- mitko 16y agoCan anybody write a macro statement this way? Something like: macro square(x): return exec("#{x}*#{x}") might be useful. Edit: can anybody help me how about the comments markup. I tried searching around but couldn't find anything.