4 ms·
Something super simple but that really entertained me when learning lisp: (loop(print(eval(read))) to have a REPL. (Just reverse the letters, easy enough
by Insanity 7y ago
Something super simple but that really entertained me when learning lisp:
(loop(print(eval(read)))
to have a REPL. (Just reverse the letters, easy enough to remember).
That to me is elegance. It's simple yet powerful, and just 4 words really.
- mg 7y agoNice. I immediately had to try the same in PHP. To make a working repl with newlines in the output etc, this is what I a came up with: while(1) {eval(fgets(STDIN));echo "\n";}; I then tried it on the command line like this: php -r 'while(1) {eval(fgets(STDIN));echo "\n";};'; Hurray, it prompted me for input! So I typed: for ($i=0;$i<10;$i++) echo $i; Which got me: 0123456789 So far so good. I wondered: Can we now run the repl in the repl? So I typed: while(1) {eval(fgets(STDIN));echo "\n";}; It kept prompting me for input. Am I in a REPL in a REPL now? I typed: echo "Hello from a REPL in a REPL!"; And the reply was: Hello from a REPL in a REPL! I'm not totally sure if I believe it though.
- sillysaurusx 7y agoIt is that simple! It has practical benefits. For example, if you can call that code from somewhere specific in your program, which is handy for debugging. If your `eval` function takes a lexical environment, you can also implement a debugger easily. To test whether your logic is working properly, make your repl print out a different character when it prompts for input. For example, the toplevel repl can print out "> " whereas the inner repl prints out "repl> " For bonus points, your repl should exit if you type Ctrl-D. That way you can go from the inner repl to the outer repl, and from there it should exit your program.
- bitwize 7y agoSounds like a Nine Inch Nails song. "I am in a REPL in a REPL in a REPL, Running all my code in nested loops..." https://youtu.be/pVB_DI4ajKA https://youtu.be/pVB_DI4ajKA
- 74ls00 7y agoDon’t you have the cart before horse; isn’t the acronym derived from this defintion?
- Insanity 7y agoYeah REPL comes from this definition of "reading, evaluation, printing, looping". But in lisp you write it in reverse order, "Loop, print, evaluate, read". I'm not saying the acronym came before or after the LISP code :P
- badfrog 7y agoThis is the first example I've seen in this thread that I would consider beautiful. The rest are neat tricks, but quite difficult to understand, so I wouldn't be happy to see them in production code.
- monsieurbanana 7y agoI mean... You really shouldn't have an unchecked repl in your production code either.
- Insanity 7y agoTrue but at least you'd understand what's going on :D