Lurker News
Preferably an elegant snippet rather than an entire (well engineered) codebase.

Comments (380) 116 threads

Earlier comments
zengargoyle2 replies#
Pick a random line from a file / stream without knowing how many lines there are to choose from in one pass without storing the lines that have been seen.

  perl -e 'while(<>){$x=$_ if rand()<=(1/$.)}print $x'
For each line, pick that line as your random line if a random number (0<=n<1) is less than the reciprocal of the number of lines read so far ($.).

It hits my elegant bone. Only one line... rand < 1/1, pick it. Two lines, same as one, but the second line has a 1/2 change of replacing line one. Third line same as before but gets a 1/3 chance of taking the place of whichever line has survived the first two picks. At the end... you have your random line.

visarga4 replies#
Does this algorithm guarantee uniform probability for all lines? Seems like the original ordering of the lines is a factor.
ChristianGeek#
IMO it’s a lot clearer if it’s not in Perl

What isn’t?

patio11#
If you want to monte carlo it, https://gist.github.com/patio11/546c64c927c749c69964b18527fa... ; feel free to adjust the constants upwards and/or do a chi squared test after doing so.

It didn't sound plausible to me (because I misunderstood what the algorithm was; yay perl), hence quickly testing it, but it seems to work, and after appreciating what the algorithm actually is (see sibling replies), it not only works but it _should_ work. (There is a CS versus engineering joke in here, somewhere.)

microtherion1 reply#
Same number of keystrokes, but IMHO more idiomatic & readable:

    perl -ne '$x=$_ if rand()<=(1/$.); END { print $x }'
zengargoyle#
Ha, that's how I originally wrote it, but I thought I should get rid of -n and END{} in an attempt to ward of the eww Perl comments. Sigh.

But at least now I know that it's called Reservoir Sampling. I had wondered how to generalize it to wanting N lines.

Insanity3 replies#
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.

mg2 replies#
Nice. 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#
It 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#
Sounds 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

74ls001 reply#
Don’t you have the cart before horse; isn’t the acronym derived from this defintion?
Insanity#
Yeah 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

badfrog1 reply#
This 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.
monsieurbanana1 reply#
I mean... You really shouldn't have an unchecked repl in your production code either.
Insanity#
True but at least you'd understand what's going on :D
labria4 replies#

  (define eval-expr
    (lambda (expr env)
      (pmatch expr
        [`,x (guard (symbol? x))
          (env x)]
        [`(lambda (,x) ,body)
          (lambda (arg)
            (eval-expr body (lambda (y)
                              (if (eq? x y)
                                  arg
                                  (env y)))))]
        [`(,rator ,rand)
         ((eval-expr rator env)
          (eval-expr rand env))])))
There's an amazing talk about it: https://www.youtube.com/watch?v=OyfBQmvr2Hc
chombier#
Once you've seen this one, it's difficult not to rank it first :)
estomagordo1 reply#
Great. In 90 minutes I may be able to know what you're talking about.
estomagordo1 reply#
Is it a complete lisp interpreter, written in lisp?
quickthrower2#
Y Combinator?
seisvelas2 replies#
Oh my God, his Lisp interpreter in Python: amazing. At the time I was just getting a grip with Python and starting in Lisp, it came at just the right moment in my autodidaction.

Really really good, although for a lot of people here it might be a little elementary (but then, the best code always feels elementary even when doing something advanced!)

Load more comments