Ask HN: What is the most beautiful piece of code you've ever read? - <AUTHOR> Preferably an elegant snippet rather than an entire (well engineered) codebase. <comment><USER2> For me it's a BASIC one-liner which generates mazes

      10 PRINT CHR$ (205.5 + RND (1)); : GOTO 10

I found this specific one via slashdot[1], but something similar, which I've never managed to find/replicate, was used to generate mazes on the Atari 800 XL at my school when I was a kid.

[1] [https://developers.slashdot.org/story/12/12/01/1847244/how-d...](https://developers.slashdot.org/story/12/12/01/1847244/how- does-a-single-line-of-basic-make-an-intricate-maze)

<comment><USER3> No, it does not generate a maze. It generates a random sequence of \s and /s, that can trigger a maze being generated in a typical user's mind.

This is the art of illusion.

<comment><USER4> What is a maze? One could argue that if the user perceives a maze, then it produces a maze.

<comment><USER5> > One could argue that if the user perceives a X, then it produces a X.

This can be stretched to turn anything into anything else. For example, why can't this comment be a maze? In that case 10 REM; 20 END is my even shorter, more elegant maze program because I see a maze in it.

Some constraints that are typically implied when people say "computer generated mazes":

\- They are solvable (have a start and end)

\- OR they loop endlessly with no dead ends.

\- Walls and spaces consume 1 element on the grid.

\- No space on the grid is surrounded by all 4 NWSE walls.

<comment><USER6> >> _One could argue that if the user perceives a X, then it produces a X. >This can be stretched to turn anything into anything else. For example, why can't this comment be a maze?_

Because unlike the one-liner nobody perceives it as a maze, so the "this can be stretched to turn anything into anything else" argument is tenuous...

</comment></comment></comment></comment></comment><comment><USER7> The one that blew my mind when I was in college was a simplified version of quicksort in Haskell. It's just so elegant and clean.

        quicksort :: Ord a => [a] -> [a]
        quicksort [] = []
        quicksort (p:xs) = (quicksort lesser) ++ [p] ++ (quicksort greater)
            where
                lesser = filter (< p) xs
                greater = filter (>= p) xs

Now surely someone may come along and point out how this isn't a _true_ quicksort[0] because it doesn't partition the elements in place, but it's more of the simplicity of the logic and its readability that showed me how beautiful functional code can be.

[0] [https://stackoverflow.com/questions/7717691/why-is-the- minim...](https://stackoverflow.com/questions/7717691/why-is-the-minimalist- example-haskell-quicksort-not-a-true-quicksort)

<comment><USER8> Quick sort comes with a steep penalty. Worst case is O(n^(2)). The reason quicksort is good is because it's in place. Once you throw away the in place aspect of quick sort, it's straight up bad.

This implementation of quicksort is actually a great example of why functional programming sucks. It silently transforms an O(1) space algorithm into an O(n) space one, and adds an enormous constant time overhead.

Algorithms that are optimal under the mutable data assumption are different than algorithms that are optimal under the constant data assumption. So a normal programmer might sort via quicksort in Haskell because it's the optimal sort in imperative languages even though naive Haskell quicksort is objectively worse in every way than naive Haskell mergesort.

Performant programming in Haskell requires a much more intimate understanding of the underlying architecture than performant programming in, for instance, C++. And that's a very low bar.

<comment><USER9> > It silently transforms an O(1) space algorithm into an O(n) space one, and > adds an enormous constant time overhead.

Please tell me what imperative quicksort algorithm has O(1) space. All versions I've seen and could recall use recursion; although each recursive call uses O(1) space, in the worst case of bad pivot element selection each recursive call would only really sort one element resulting in a worst-case O(n) space. Use of randomization would result in a high probability of choosing a good pivot element, but even then you can expect approximately O(log n) space.

Also would like to see why you think the Haskell version has enormous constant time overhead. Where do you think this overhead comes from? If you are comparing to an equivalent program in C++ then sure allocations and stuff, but compared with the typical Haskell list-processing programs I don't see any significantly larger overhead.

<comment><USER10> For non recursive quicksorts see code at bottom of this link: [https://www.geeksforgeeks.org/iterative-quick- sort/](https://www.geeksforgeeks.org/iterative-quick-sort/)

<comment><USER9> That link basically just simulates recursion by defining a stack in the function. It recognizes that in the recursive version among the stack variables only the two indexes need to be stored so it stores them. It is even less space efficient than the recursive version because it always allocates O(n) space.

</comment></comment></comment></comment></comment><comment><USER11> I began coding in IBM/LCSI PC Logo. The first line of code I ever wrote was:

      FD 100

That's the "hello, world" of turtle graphics in Logo. While probably not as beautiful as the several splendid examples posted in this thread, that simple line of code changed my world. I could make stuff happen in an otherwise mostly blank monochrome CRT display. Until then I had seen CRTs in televisions where I had very little control on what I see on the screen. But now, I had control. The turtle became my toy and I could make it draw anything on a 320 x 250 canvas.

The next beautiful piece of code I came across in the same language was:

      REPEAT 360 [FD 1 RT 1]

The code above draws an approximation of a circle by combining 360 short line segments. It showed me how control flow can be used elegantly to express complex ideas in a simple expression. And then I came across this:

      REPEAT 20 [REPEAT 180 [FD 1 RT 2] RT 18]

The above code draws 20 overlapping circles. The output looks like this: [https://susam.in/files/blog/dosbox- logo-1.png](https://susam.in/files/blog/dosbox-logo-1.png) .

At an impressionable age of 9, reading and writing code like this, and using simple arithmetic, geometry, logic, and code to manipulate a two-dimensional world had a lasting effect on me. I like to believe that my passion for software engineering as well as my love for writing code, sharing code, and open source development are a result of coming across these beautiful code examples early in my life.

<comment><USER12> The true beauty of Logo comes in the realization that you can add your own words to it, and that all these specialist words you devise are themselves first-class citizens of the language, of syntax and status equal to its generic builtins. Hence:

        TO CIRCLE
        REPEAT 360 [FD 1 RT 1]
        END

        TO FLOWER
        REPEAT 20 [CIRCLE RT 18]
        END

and so on ad infinitum, until you arrive at a complete custom vocabulary that concisely and precisely expresses the particular concepts and behaviors of interest and importance to you. In doing so, you move from thinking algorithmically (which is glorified spaghetti) to thinking _compositionally_ , which is the key to _scalability_ – managing complexity as your needs and ambitions grow.

Whereas Algol-y languages treat user-defined vocabulary as second-class citizens, beneath their own privileged built-ins. Which is a ridiculous of status when you consider which is actually important to the user: precise, powerful, tailored words that describe their particular problem, or the crude primitive undifferentiated building blocks that the language dumps out of the box?

The beauty of bottom-up programming (as any Lisp fule kno:) is that endlessly tests your own understanding of the problem domain: to define effective, productive words you must have some idea of what you're talking about; you can't help but learn the foundations of the problem space as you go. There's a basic _humility_ to this approach; there's nowhere to hide laziness or ignorance.

Whereas in top-down programming it's much too easy for highly-educated highly- paid absolute know-nothings to bullshit eternally, constructing great theatrical class architectures; grand mechanical castles in the sky that look all very difficult and impressive to observers while never saying anything relevant or useful.

That key switch from algorithmic to compositional thinking is not a natural conceptual leap for self-learners – it takes a carefully directed prod at a particular point in the learning curve to jump those rails – but it opens up worlds. #PlatosCave

<comment><USER13> Thanks for writing this. I think you've explained why I've always liked the ability to invoke functions without parentheses. I always thought it simply appealed to my sense of aesthetics, and I've had somewhat of a hard time defending it but now that you mention it, building my own first-class primitives is a big part of it.

</comment></comment></comment><comment><USER14> John Carmack's Fast Inverse Square Root: [https://en.wikipedia.org/wiki/Fast_inverse_square_root#Overv...](https://en.wikipedia.org/wiki/Fast_inverse_square_root#Overview_of_the_code). The first time I really and truly felt that people approach problems differently from how I, by default, go about them.

<comment><USER15> it's the antithesis of maintainable code. But given that one is unlikely to want to change from calculating the inverse square root to inverse cube root or any other variation....

<comment><USER16> I disagree strongly. This code is very maintainable: it does not have dependencies, it is trivial to test, it is wickedly short, and with the appropriate comment there is no confusion regarding its purpose. Also, its field of applicability is clear from the context: replace this code with a call to fsqrt if you happen to have a fast hardware implementation of it. It is the most easily maintainable code, ever!

<comment><USER15> the one maintainability metric, and i think is the most important one, is whether it's easy to modify (to make it do something slightly different).

You'd be hard pressed to write an inverse square cube without basically rewriting the whole function. There's nothing that can be reused. The only saving grace is that it is side-effect free, so replacement is trivial, unlike a lot of other code that's not maintainable.

<comment><USER17> Your metric is only applicable within the context of the problem domain. In 3-d graphics, the inverse square root (1 divided by the square root of x) is an extremely common operation (such as for normalizing vectors), but the inverse cube root pretty much isn't used, so it's safe to assume you will not need to extend it to arbitrary powers.

As the designer of the code, you would understand that the inverse square root is a standalone problem.

</comment></comment></comment></comment></comment><comment><USER18> 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.

<comment><USER19> Does this algorithm guarantee uniform probability for all lines? Seems like the original ordering of the lines is a factor.

<comment><USER20> The OP should have mentioned that it's this algorithm:

[https://en.wikipedia.org/wiki/Reservoir_sampling](https://en.wikipedia.org/wiki/Reservoir_sampling)

IMO it's a lot clearer if it's not in Perl ...

The pseudocode in Wikipedia also avoids division.

<comment><USER21> _IMO it's a lot clearer if it's not in Perl_

What isn't?

</comment></comment></comment></comment><comment><USER22> 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.

<comment><USER23> 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.

<comment><USER24> 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.

</comment></comment></comment><comment><USER25>
      (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](https://www.youtube.com/watch?v=OyfBQmvr2Hc)

<comment><USER26> Great. In 90 minutes I may be able to know what you're talking about.

<comment><USER26> Is it a complete lisp interpreter, written in lisp?

<comment><USER27> Yes, it uses pmatch behind the scene to match your expr against the evaluator.

[https://github.com/webyrd/quines/blob/master/pmatch.scm](https://github.com/webyrd/quines/blob/master/pmatch.scm)

I have to agree, this like rank #1 in my book!

</comment></comment></comment></comment><comment><USER28> Any of Norvig's notebooks, [http://www.norvig.com/ipython/README.html](http://www.norvig.com/ipython/README.html), especially his Concrete Introduction to Probability [https://nbviewer.jupyter.org/url/norvig.com/ipython/Probabil...](https://nbviewer.jupyter.org/url/norvig.com/ipython/Probability.ipynb).

<comment><AUTHOR> 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!)

<comment><USER29> IMHO, the most beautiful lisp interpreter in a language that is not lisp is this one in prolog.

[https://www.metalevel.at/lisprolog/](https://www.metalevel.at/lisprolog/) [https://www.metalevel.at/lisprolog/lisprolog.pl](https://www.metalevel.at/lisprolog/lisprolog.pl)

</comment></comment></comment><comment><USER30> I'd have to think long and hard for the _most_ beautiful code I've ever read, but I think the classic K&R "strcpy" comes pretty close:

      void strcpy(char *s, char *t) {
          while (*s++ = *t++);
      }

It's short, elegant, and quite readable to the trained eye–a bit sharp too, but if you use it right it's quite functional.

<comment><USER31> I dunno. The security ramifications of those few lines of code make me squirm. It's like looking at a very beautifully constructed foot gun.

I wonder how much damage that code has caused.

<comment><USER32> At the time the code was written, the security ramifications were not quite the same as they are now. Even now, I would suggest that there are times where such a construction would be just fine.

<comment><USER33> Nit, but an important one: the security ramifications were just as large than as now, they were just largely unknown at the time.

</comment></comment></comment></comment><comment><USER34> This PNG parser in Elixir uses pattern matching in an elegant way.

[https://gist.github.com/zabirauf/29c89a084901cab8bc6b](https://gist.github.com/zabirauf/29c89a084901cab8bc6b)

Parsing binary data can be...nontrivial. The beauty is in the code that doesn't exist.

</comment><comment><USER29> Exploit codes are often the most beautiful code I read, they are usually small and take some dazzling brilliance to push the computer and make it do what it wasn't.

I can remember the first code that showed how to exploit IFS, race conditions via symlink, the classic "smashing the stack", RTM's worm.

Beauty of a code to me has nothing to do with the formatting, comments, documentations, but everything to do with the mind that bent it into place. Most of the beautiful code I have ever seen would be classified as ugly, spaghetti, not production worthy.

<comment><USER35> >RTM's worm

I had absolutely no idea until now that RTM co-founded y-combinator. I remember him from mentioned in Bruce Sterling's The Hacker Crackdown and Clifford Stoll's The Cookoo's Egg as well as an occasional Phrack article.

[https://en.wikipedia.org/wiki/Robert_Tappan_Morris](https://en.wikipedia.org/wiki/Robert_Tappan_Morris)

<comment><USER36> He was one of PG's Viaweb cofounders as well. He also introduced PG to the third cofounder, Trevor Blackwell.

</comment></comment></comment><comment><USER37> The SQLite source tree and DRH code in general are truly piece of art. Almost every line of code is carefully commented. Despite the complexity of the project, you'll learn a lot of practical concepts including expression tree generation, bytecode execution, how to test your code and so forth.

<comment><USER38> I love the SQLite guy. His own version control, his own DB engine; you can tell from the site that he's an individualist!

<comment><USER39> He mentioned on a podcast that he even uses his own text editor.

<comment><USER40> Wow! Do you remember which podcast? Now I am interested in this interview!

<comment><USER41> [https://changelog.com/podcast/201](https://changelog.com/podcast/201)

</comment></comment></comment></comment></comment><comment><USER42> Implementing FizzBuzz with explicit monoidal operations has been one of those things that I go back to and marvel at the simplicity and elegance of: [http://dave.fayr.am/posts/2012-10-4-finding- fizzbuzz.html](http://dave.fayr.am/posts/2012-10-4-finding-fizzbuzz.html)

It really inspired me to get better at seeking out the fundamental operations of whatever I was implementing.

<comment><USER43> That is great.

</comment></comment><comment><USER44> I think c4 (a C compiler in four functions, hence the name) is pretty neat.

[https://github.com/rswier/c4/blob/master/c4.c](https://github.com/rswier/c4/blob/master/c4.c)

<comment><USER45> That's my choice too. It's a C-subset, but more than a compiler; it includes a bytecode VM interpreter too. The best part about it is that it's tiny, yet very readable for its size and functionality.

</comment></comment><comment><USER46> Considering the magnitude of its impact on science, engineering and culture (as well as the tremendous force released), this line from the IGNITION subroutine in the BURN_BABY_BURN module of the Apollo AGG source code does it for me:

[https://github.com/chrislgarry/Apollo-11/blob/master/Luminar...](https://github.com/chrislgarry/Apollo-11/blob/master/Luminary099/BURN_BABY_BURN --MASTER_IGNITION_ROUTINE.agc#L417)

<comment><USER47> I love the comments in that file. Especially these two:

        # HONI SOIT QUI MAL Y PENSE

and

        # NOLI SE TANGERE

</comment></comment><comment><USER48> For me it's the unix example in [1] _" AT&T Archives: The UNIX Operating System"_.

        $ makewords sentences | lowercase | sort | unique | mismatch -

It reads a file called sentences then prints the words that are not spelled correctly.

To me it's; concise, expressive, flexible, modular... Which makes it beautiful...

[1] [https://youtu.be/tc4ROCJYbm0](https://youtu.be/tc4ROCJYbm0)

</comment><comment><USER49> For me, the answer is - The code that never existed.

Not to sound cheeky but eliminating code, is a beautiful thing. Less code is easier to maintain, understand, and faster to run. So the less code you can achieve, the better overall the software will be.

<comment><USER50> This brings me to a very nice regular expression. It is the one being recommended in

        RFC3986 "Uniform Resource Identifier (URI): Generic Syntax"
        by  T. Berners-Lee, R. Fielding and L. Masinter

        https://tools.ietf.org/html/rfc3986

to parse an URI. Having seen so many regular expressions, that try to match it all, this regex tries to match as little as possible, while, at the same time, matches any string, because it matches no string. It does not define _what_ to match, but _what_ not to match and making every match optional.

According part from the spec:

        ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
         12            3  4          5       6  7        8 9

        The numbers in the second line above are only to assist readability;
        they indicate the reference points for each subexpression (i.e., each
        paired parenthesis).  We refer to the value matched for subexpression
        <n> as $<n>.  For example, matching the above expression to

          http://www.ics.uci.edu/pub/ietf/uri/#Related

        results in the following subexpression matches:

          $1 = http:
          $2 = http
          $3 = //www.ics.uci.edu
          $4 = www.ics.uci.edu
          $5 = /pub/ietf/uri/
          $6 = <undefined>
          $7 = <undefined>
          $8 = #Related
          $9 = Related

        where <undefined> indicates that the component is not present, as is
        the case for the query component in the above example.  Therefore, we
        can determine the value of the five components as

          scheme    = $2
          authority = $4
          path      = $5
          query     = $7
          fragment  = $9

<comment><USER51> One of my favorite RFCs for sure, and it's a beautifully simple and useful regex. It's a shame RFCs seem to have fallen out of fashion, the WHATWG URL spec is an unreadable mess of a monster, not least the parsing section: [https://url.spec.whatwg.org/#url-parsing](https://url.spec.whatwg.org/#url- parsing)

</comment></comment></comment><comment><USER52> Duff's Device: [https://en.wikipedia.org/wiki/Duff%27s_device](https://en.wikipedia.org/wiki/Duff%27s_device)

Very elegant use of the fall-through behavior of the swtich statement.

<comment><USER53> For those unaware, * do not use this on modern systems. *

Normal for-loops are much faster than they were when Duff's Device was invented, since they take advantage of modern branch prediction.

<comment><USER54> That depends on how large the misprediction penalty is and how many times the branch executes. Branch prediction isn't magic. It never makes branches beneficial. The best it can do, with perfect accuracy, is bring the amortized misprediction penalty down to zero. The key is that Duff's Device also relies on branching, and it's a less predictable branch that's more likely to be mispredicted. On the other hand, one BP miss is still cheaper than several hits plus one miss at the end. On the other other hand, there are issues to consider like code size and cache turnover (favors a loop), handling of special cases where larger loads/stores can be used (favors DD), processor extensions, etc. If you're really trying to write an optimal memcpy-like function, you'll probably end up using a hybrid of several approaches - including Duff's Device.

</comment></comment></comment><comment><USER55> It's impossible to choose a favourite, but here's a beautiful snippet, courtesy of Joe Armstrong [0]

      universal_server() ->
          receive
             {become, F} ->
                 F()
          end.

[0] [https://joearms.github.io/published/2013-11-21-My- favorite-e...](https://joearms.github.io/published/2013-11-21-My-favorite- erlang-program.html)

</comment><comment><USER56> Bash fork bomb (do _not_ run, this will crash your system if it's not configured properly):

        :(){ :|:& };:

<comment><USER44> I like the Windows one, too. It looks a lot simpler as well.

      %0|%0

<comment><USER57> I don't know Windows scripting, but that looks like something you'd have to put in a file and call for it to work, instead of just running that on the command line. You can do the same thing on Unix systems. Writing

      $0|$0

on a file and running it should also work as a fork bomb.

</comment></comment></comment><comment><USER58> [https://norvig.com/spell-correct.html](https://norvig.com/spell-correct.html)

Changed the way I think about code

<comment><USER59> Thank you for the share! This was excellent.

Could you leave a sentence or two about how it made you "change the way [you] think about code"?

<comment><USER58> Because of Norvig's spelling corrector, my measure for good code is whether or not I can understand what it's supposed to be doing, and how it's supposed to work, from reading it in one pass.

This code passes that test. Before reading it I would have never thought that could be a goal— I couldn't imagine it was possible to know what a program does without comments and documentation.

When I heard the word "readable" from others, I understood it as "parsable". From an OO context, I thought readable meant neatly formatted lines that let you say "ah, yes, this is an if statement", "this is a constructor", and so on, but with no idea what the code actually does or means to do.

Norvig's spelling corrector is better read without comments. The names of the functions tell you what you need to know— their purpose, and their implementations tell you exactly what the author thinks they mean.

It's "declarative": "def correction(word):..." means exactly "the correction of a word is ___", "def candidates(word):..." means exactly "the candidate corrections of a word are ___". There's a strong functional/LISP influence here, which I only learned later.

Because this code demonstrated it was possible, my standard for all code is that it should tell you what it does from one reading. Most code (including my own!) doesn't come close, but aiming for that goal has tons of good effects on difficult code.

<comment><USER59> Thank you very much for your response!

</comment></comment></comment></comment><comment><USER60> Haskell allows you to define the full list of prime numbers in just two lines:

      module Primes where

      primes = 2 : filter isPrime [3..]
      isPrime x = all (\y -> mod x y /= 0) $ takeWhile (\y -> y * y < x) primes

The beauty of this is that it's self-referential. The list `primes` is built by filtering all the natural numbers for prime numbers, using the predicate `isPrime` which itself uses the list `primes`. The only caveat is that we need to encode that 0 and 1 are not prime numbers, but 2 is a prime number, to provide the base cases for the recursion. Furthermore, `isPrime` uses that each non-prime number has at least one prime factor less than or equal to its square root, to ensure that it only needs to look at a finite number of possible prime factors.

If you have GHC in your repo, you can test this by putting it in a file and running `ghci` with the file as the only argument. It will give you a REPL where `primes` and `isPrime` are in scope:

      *Primes> isPrime 200
      False
      *Primes> take 10 primes
      [2,3,5,7,11,13,17,19,23,29]

<comment><USER61> It is also dirt slow. This is just trial division, done in a lazy fashion.

At least it is better than the one some haskellers call the sieve of erathostenes (it isn't the sieve of erathostenes), which is so god-awful that I almost vomit every time I see it.

The real lazy sieve of erathostenes is a thing of wonder! There is a paper describing it called "the genuine sieve of erathostenes" and it can be found by googling.

<comment><USER62> this?

      sieve :: Integral a => a -> [a]
      sieve l =
          sieve' [2..l] []
        where
          sieve' (p:ns) ps =
                sieve' (filter (\x -> rem x p /= 0) ns) (p : ps)
          sieve' [] ps =
              reverse ps

<comment><USER61> The lazy sieve i have seen, taken from the paper mentioned in my post:

        primes = sieve [2..]
        sieve (p : xs) = p : sieve [x | x <− xs, x 'mod' p > 0]

</comment></comment></comment></comment><comment><USER63> Curiously Recurring Template Pattern (CRTP) [0] in C++.

      class Derived : public Base<Derived>

[0] [https://en.wikipedia.org/wiki/Curiously_recurring_template_p...](https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern)

<comment><USER64> That's awesome. I ran into this situation in C#, and looks like it is useful in some cases.

[https://zpbappi.com/curiously-recurring-template-pattern- in-...](https://zpbappi.com/curiously-recurring-template-pattern-in-csharp/)

<comment><USER65> tl;dr: "Generally, whenever you need the derived class information in the base class, you are probably looking for CRTP."

</comment></comment></comment><comment><USER66> If you create an executable file with the following contents, and run it, it will delete itself.

        #!/bin/rm

<comment> Iwan-Zotow There is a better example - original /bin/true source. Presented to you below.

<comment><USER67> Compare that with the version in GNU Coreutils[1] that is 50+ lines long so that false[2] can be written as:

#define EXIT_STATUS EXIT_FAILURE

#include "true.c"

[1] [https://github.com/coreutils/coreutils/blob/master/src/true....](https://github.com/coreutils/coreutils/blob/master/src/true.c)

[2] [https://github.com/coreutils/coreutils/blob/master/src/false...](https://github.com/coreutils/coreutils/blob/master/src/false.c)

</comment></comment></comment><comment><USER68> Waiting for a keypress in ZX81 BASIC (maybe it's the opposite of elegant, but I remember it as the first time seeing a kind of easter egg in code):

        10 PAUSE 4E4

"PAUSE n

stops computing & displays the picture for n frames of the television (at 50 frames per second, or 60 in America). n can be up to 32767, which gives you just under 11 minutes; if n is any bigger then it means 'PAUSE for ever'.

A pause can always be cut short by pressing a key"[0]

(4E4 = 4*10^4 = 40000)

[0] [http://www.worldofspectrum.org/ZX81BasicProgramming/chap19.h...](http://www.worldofspectrum.org/ZX81BasicProgramming/chap19.html)

</comment><comment><USER69> That's a way to loaded and bait like question. Why not ask for "the most elegant snippet" instead?

There are beautiful code bases like DOOM source or SAT solvers that are like super models beautiful. Complete and hard to improve. Marvel at from a distance.

There is beautiful code in the libraries everybody uses all the time. All the lib* code. Somebody to marry. Discover the good beauty over time.

And then there is the beautiful snippet of clever code at the bar, quick to love, but one you get to know him it's much more trouble than he's worth.

</comment><comment><USER70> This one is kind of contrived, but a work of mad genius. Mandelbrot code that resembles Mandelbrot, in Python 2:

        _                                      =   (
                                                255,
                                              lambda
                                       V       ,B,c
                                     :c   and Y(V*V+B,B,  c
                                       -1)if(abs(V)<6)else
                       (              2+c-4*abs(V)**-0.4)/i
                         )  ;v,      x=1500,1000;C=range(v*x
                          );import  struct;P=struct.pack;M,\
                    j  ='<QIIHHHH',open('M.bmp','wb').write
        for X in j('BM'+P(M,v*x*3+26,26,12,v,x,1,24))or C:
                    i  ,Y=_;j(P('BBB',*(lambda T:(T*80+T**9
                          *i-950*T  **99,T*70-880*T**18+701*
                         T  **9     ,T*i**(1-T**45*2)))(sum(
                       [              Y(0,(A%3/3.+X%v+(X/v+
                                       A/3/3.-x/2)/1j)*2.5
                                     /x   -2.7,i)**2 for  \
                                       A       in C
                                              [:9]])
                                                /9)
                                               )   )

[https://codegolf.stackexchange.com/questions/23423/mandelbro...](https://codegolf.stackexchange.com/questions/23423/mandelbrot- image-in-every-language)

</comment><comment><USER71> This is very common in Elm but it blew my mind after years of programming in Python. In Python it is very easy to raise an IndexError by getting an element from a list by index that doesn't exist. eg.

        # python
        names = []

        names[0]  # <- raises IndexError

In Elm you are forced to always consider this possibility.

        # Elm
        names = []

        case List.head names of
            Just name ->
                name
            Nothing ->
                "empty"

<comment><USER72> Idiomatic python:

      v = names[0] if names else "empty"

<comment><USER73> Yes, but the point is you can forget the check in python but not in Elm.

</comment></comment></comment><comment><USER74> The simple regexp matcher by Rob Pike: [https://www.cs.princeton.edu/courses/archive/spr09/cos333/be...](https://www.cs.princeton.edu/courses/archive/spr09/cos333/beautiful.html)

<comment><USER75> Pike's code should be studied in schools.

</comment></comment><comment><USER76> Someone once posted a C program here on HN, where each line, even the comments, seemed to "line up" in 6- or 8- character blocks with a space in between. It made the whole program look sort of like a table.

I felt it was sort of like poetry. I unfortunately no longer have a link to it, and once looked very hard but couldn't find it.

I would be extremely appreciative of someone else saw it and had a link. If I recall correctly it was a type of interpreter, I remember it having code for parsing.

<comment><USER77> Most likely an IOCCC entry, but there are a lot that correspond to this description. Maybe you can find it back looking at previous winners of the contest: [http://www.formation.jussieu.fr/ars/2000-2001/C/cours/COMPLE...](http://www.formation.jussieu.fr/ars/2000-2001/C/cours/COMPLEMENTS/DOC/www.ioccc.org/years- spoiler.html)

<comment><USER76> I appreciate your help, but I feel like its unlikely to be in there since it wasn't really obfuscated - it was meant to be clear in some sense of the word and had a bunch of comments explaining it.

The comments sounded natural, but lined up so each Nth column was a space (or punctuation) all of the way down the code. None of the things I am seeing in that list seem to have quite the same layout.

There was some comment about it like "some people feel code should be beautiful to enjoy debugging" or something along those lines but I don't really remember.

I have been looking for a long time though and really wish I had saved it properly when I first saw it.

</comment></comment></comment><comment><USER78> Bit tricks. Like

        public static int bitCount(int i) {
            i = i - ((i >>> 1) & 0x55555555);
            i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
            i = (i + (i >>> 4)) & 0x0f0f0f0f;
            i = i + (i >>> 8);
            i = i + (i >>> 16);
            return i & 0x3f;
        }

It was like magic for me when I encountered it first time.

<comment><USER79> Came here to say this, I first saw this in the book Hackers Delight which is full of 200X-me's mind blowing stuff. It really opened a door to writing (arb)GPU shaders where at the time if's weren't allowed and trying to cut branches from PS2/GameCube/Xbox code

</comment></comment><comment><USER80> # Permutations of a list:

\- haskell:

      perms [] = [[]]
      perms xs = [ x:ps | x <- xs , ps <- perms ( xs\\[x] ) ]

\- js: (using [https://github.com/tc39/proposal-slice- notation](https://github.com/tc39/proposal-slice-notation) for conciseness)

      const perms = xs => xs.length === 0
        ? [[]]
        : xs.flatMap((xi, i) => perms([...xs[0:i], ...xs[i+1:]).map(xsi => [xi, ...xsi])

# Cartesian product of 2 or n lists

\- haskell:

      cart2 xs ys = [(x,y) | x <- xs, y <- ys]

      cartn :: [[a]] -> [[a]];
      cartn [] = [[]]
      cartn(xs:xss) = [x:ys | x <- xs, ys <- yss]
                            where yss = cartn xss

\- js:

      const cart2 = (xs, ys) => xs.flatMap(x => ys.map(y => [x,y]));

      const cartn = (...args) => args.reduce((yss, xs) => yss.flatMap(ys => xs.map(x => [...ys, x])), [[]]);
      // or recursive
      const cartn = (xs, ...xss) => xss.length === 0
        ? xs
        : xs.flatMap(x => cartn(...xss).map(y => [x,y]))

<comment><USER44> Until now I didn't know about flatMap() and flat(). Thanks for this!

</comment></comment><comment><USER81> NEW

10 PRINT "HELLO"

20 GOTO 10

30 END

RUN

I remember typing this on an ASR-33 and being amazed. _I_ made a computer do that. Then I hit Ctrl-C and learned how to make a paper tape with a "here is" leader, turning the paper punch off, then typing "LIST" and turning it back on before hitting RETURN.

A PDP-11/10 with 16K and 3 20mA TTYs connected, no disks, no storage except paper tape.

I've still got that paper tape somewhere, it's 42 years old now.

<comment><USER82> Had a KSR-33 wired up to a Synertek single-board 6502 kit... never did get the paper tape working, but man was it weirdly cool to be typing on a 50 pound behemoth to put numbers in the 2kB memory of a 6 ounce PC board.

</comment></comment><comment><USER83> A fully graphical calculator app in Rebol is just a few lines of code. The formatting looks pretty legible at the below link if you scroll down a bit.

REBOL [title: "Calculator"] view layout [ origin 0 space 0x0 across style btn btn 50x50 [append f/text face/text show f] f: field 200x40 font-size 20 return btn "1" btn "2" btn "3" btn " \+ " return btn "4" btn "5" btn "6" btn " \- " return btn "7" btn "8" btn "9" btn " * " return btn "0" btn "." btn " / " btn "=" [ attempt [f/text: form do f/text show f] ] ]

[https://easiestprogramminglanguage.com/easiest_programming_l...](https://easiestprogramminglanguage.com/easiest_programming_language.html)

<comment><USER84> Nice to see Rebol and Red mentioned!

Here's a Red version of the calculator: [https://github.com/red/code/blob/master/Showcase/calculator....](https://github.com/red/code/blob/master/Showcase/calculator.red) You can see the syntax is very close. We strive for compatibility with Rebol, but are also changing things that we feel could be improved.

A small twist on the UI can use a `panel`, which supports a divider option to make grid layout easier. e.g., for 4 items across, you can do this:

      view [
         style b: button 50x50 bold
         panel 4 [
              b "1"  b "2"  b "3"  b "+"
              b "4"  b "5"  b "6"  b "-"
              b "7"  b "8"  b "9"  b "*"
              b "0"  b "."  b "/"  b "="
         ]
      ]

Red is fully open source, and can be compiled. Most code anyway. You can write code that is too dynamic to compile until we go JIT. Red is bootstrapped in Rebol, but will be self hosted next year. It is also its own, entire, toolchain. Red compiles to Red/System, a low (C) level dialect/EDSL, which compiles directly to machine code. You can mix and match the two in apps as well.

We're still alpha, and have a lot of work ahead: [https://www.red- lang.org/](https://www.red-lang.org/)

If you liked Rebol, check us out, and help create the future.

<comment><USER84> Our main chat is at [https://gitter.im/red/red](https://gitter.im/red/red)

</comment></comment></comment><comment><USER85> At first, incomprehensible. Given time, the internal consistency shines through. Worth spending a few hours reading and contemplating:

[https://code.jsoftware.com/wiki/Essays/Incunabulum](https://code.jsoftware.com/wiki/Essays/Incunabulum)

</comment><comment><USER86> Transposing a matrix in Python is pretty neat.

      >>>list(zip(*[(1, 2, 3), (4, 5, 6), (7, 8, 9)]))
      [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

</comment><comment><USER87> It's a bit of a tricky question because you can have a beautiful snippet entangled in a mess of a codebase.

I think a much better question would be most beautifully structured codebase.

Code, as a snippet, or line, is constantly struggling between poetic conciseness and verbose clarity... To which I will always pick clarity (for "the next guy"), hence not necessarily elegant.

<comment><AUTHOR> > I think a much better question would be most beautifully structured > codebase.

That would be an interesting thread too! I think gorgeous snippets have a different kind of beauty that just generally well done projects.

To me, it's kind of like comparing the beauty of a gem to the beauty of a bridge.

</comment></comment><comment><USER88> Automatic differentiation in Haskell [http://conal.net/blog/posts/beautiful- differentiation](http://conal.net/blog/posts/beautiful-differentiation)

</comment><comment><USER89> I'd guess the most beautiful code is in the part that I didn't read, because it just worked and I didn't think about it.

</comment><comment><USER90> From HAKMEM, Item 172:

      CONS: EXCH A,[EXCH A,[...[PUSHJ P,GC]]]
            EXCH A,CONS

This allocates a cons cell for Lisp on PDP-10, by using the first instruction in the routine as the head pointer of the free list. The first instruction puts the first word of the free list into A (and then clobbers that word with the original contents of A, initializing the cons cell). The second then swaps the first instruction with the first item in the free list.

The free list is simply a linked list of first instructions, which could be done because the PDP-10 was a 36-bit machine with an 18-bit address space, and the address field of an instruction was the entire right half: the same part of a word that was used as a pointer. So, when interpreted as a pointer, each of these instructions was just the pointer to the next cell.

The beautiful part to me is that, once you ran out of free list, the last word was a call to the garbage collector, which would build a free list of unreferenced cells and return a pointer to the _second_ cell (with the correct opcode field) in A; the second instruction would then finish the cons operation, leaving the address of newly allocated cons cell in A.

</comment><comment><USER91> I remember seeing Maxwell's equations written in Lisp (I believe it was in the Structure and Interpretation of Programs). This made me feel something very profound, although I am still unable to put this feeling into words.

</comment><comment><USER92> I really appreciated and missed Scala's `Some`/`None`/`Option` [1] and `lazy` constructs, so much so that I brought them with me to TypeScript.

Option provides an elegant way to handle parameters or results that may or may not be defined.

Here's a simple Option implementation:

[https://gist.github.com/mceachen/75598510275865b8cf88bb2ef80...](https://gist.github.com/mceachen/75598510275865b8cf88bb2ef804cd07)

With this you can write something like

Opt(possiblyNullResult).flatMap(ea => functionThatRequiresANonNullResultAndReturnsUndefinedOrDefined(ea)).getOrElse(() => someDefaultValue)

And here's a (very) simple implementation of lazy:

[https://github.com/photostructure/exiftool- vendored.js/blob/...](https://github.com/photostructure/exiftool- vendored.js/blob/master/src/Lazy.ts)

The idea of lazy is to allow deferment of expensive operations until they are actually needed.

The above implementation allows for something like:

const service = lazy(makeService)

Which will ensure makeService is only called once, and the first caller will have to wait for the result of makeService(). All subsequent callers re-use the first result.

It's a simple construct, but extremely handy.

[1] [https://github.com/scala/scala/blob/v2.13.1/src/library/scal...](https://github.com/scala/scala/blob/v2.13.1/src/library/scala/Option.scala#L618)

<comment><USER93> You might want to look into fp-ts. Has plenty of constructs like those, although it now favors piping calling conventions over a fluent API.

</comment></comment><comment><USER94> This 256-byte demo: [https://www.linusakesson.net/scene/a-mind-is- born/](https://www.linusakesson.net/scene/a-mind-is-born/)

</comment><comment><USER95> Lexical Scanning In Go is a charming piece of programming:

[https://m.youtube.com/watch?v=HxaD_trXwRE](https://m.youtube.com/watch?v=HxaD_trXwRE)

A good debuggable piece of code explains what it is trying to do by being clearly written and conforming to a consistent and logical model. I don't think I would ever have invented this type of lexer pattern in Go by myself, but would be very grateful to come across it in a code base I had to fix. Like _Duff's Device_ mentioned in this thread, it has just the right amount of cleverness without becoming inscrutable.

Also, if you'll excuse some avuncular pride, my niece and I wrote some code yesterday. She asked me how many times grandma's clock chimes every day and we ended up with the following Ruby:

      2 * (1..12).reduce(&:+)

<comment><USER96> Cool one liner! Here's some other languages:

Python: 2 * sum([x for x in range(1, 13)])

Haskell: 2 * sum [1..12]

<comment><USER97> You don't need the list comprehension for python - just 2 * sum(range(1, 13))

<comment> cool-RR And drop the 1, too

<comment><USER98> I prefer the explicit example for being explicit, I find it more pythonic.

GPs example is perfect Python; every character has meaning, and it's extremely readable even for non-programmers.

</comment></comment></comment></comment></comment><comment><USER99> C++ STL algorithms written by Alexander Stepanov.

<comment><USER100> Any specific ones that standout?

</comment></comment><comment><USER101>
      fibs = 0 : 1 : zipWith (+) fibs (tail fibs)

</comment><comment><USER102>
      ,[.,]

When it comes to the weird and wonderful world of esoteric programming languages, the above Brainfuck program is pretty elegant. It's a basic implementation of the echo program: printing back what the user inputs.

The complete language consists of eight single-character commands. The four used in the echo program is:

, – accept one byte of input and store it at the current memory cell

. – output the byte at the current memory cell

[ – if the value of the current memory cell is zero, jump forward to the command after the matching ]

] – if the value of the current memory is nonzero, jump back to the command after the matching [

</comment><comment><USER103> Created an account to post this:

      :v/./,/./-j

in vim will go through the whole file, joining multiple consecutive empty lines into one. Not only it is fork-bomb-level cryptic, but also showcases how you can use addresses to do advanced stuff.

Somewhat more readable version:

      :vglobal /./ .,/./- join

which is: go to every line that doesn't match (vglobal) /./ (is empty) and join lines from that line (.) to the line before (-) the next line that is not empty (/./ again).

</comment><comment><USER104> I think this was the first line of the forth in the library of an older version of jonesforth ([https://rwmj.wordpress.com/2010/08/07/jonesforth-git- reposit...](https://rwmj.wordpress.com/2010/08/07/jonesforth-git- repository/)), but now I can only find it in my port:

      : \ IMMEDIATE
            #IB @ >IN !
      ; \ We can now comment!

Implementing a forth system is unbelievably fun because of gems like this.

</comment><comment><USER105> Didn't see anyone mentioned these two pearls:

C (K&R) program that calculates PI number by measuring circle that is its code: [https://en.wikipedia.org/wiki/International_Obfuscated_C_Cod...](https://en.wikipedia.org/wiki/International_Obfuscated_C_Code_Contest#Pi)

Perl one-liner that checks if a number is prime: perl -lne '(1x$_) =~ /^1?$|^(11+?)\1+$/ || print "$_ is prime"'

</comment><comment><USER106> This number:

      4856507896573978293098418946942861377074420873513579240196520736 6869851340104723744696879743992611751097377770102744752804905883
      1384037549709987909653955227011712157025974666993240226834596619 6060348517424977358468518855674570257125474999648219418465571008
      4119086259716947970799152004866709975923596061320725973797993618 8606316914473588300245336972781813914797955513399949394882899846
      9178361001825978901031601961835034344895687053845208538045842415 6548248893338047475871128339598968522325446084089711197712769412
      0795862440547161321005006459820176961771809478113622002723448272 2493232595472346880029277764979061481298404283457201463489685471
      6908235473783566197218622496943162271666393905543024156473292485 5248991225739466548627140482117138124388217717602984125524464744
      5055834628144883356319027253195904392838737640739168912579240550 1562088978716337599910788708490815909754801928576845198859630532
      3823490558092032999603234471140776019847163531161713078576084862 2363702835701049612595681846785965333100770179916146744725492728
      3348691600064758591746278121269007351830924153010630289329566584 3662000800476778967984382090797619859493646309380586336721469695
      9750279687712057249966669805614533820741203159337703099491527469 1835659376210222006812679827344576093802030447912277498091795593
      8387121000588766689258448700470772552497060444652127130404321182 610103591186476662963858495087448497373476861420880529443

This is a 1811-digit _illegal_ prime number, which when unpacked into binary, becomes a compressed ELF executable which will decrypt DVDs. This was one of many ways used to enable people who had legally purchased a DVD with copy protection to play it on Linux. Here's the story behind finding the prime: [https://web.archive.org/web/20070223075434/http://asdf.org/~...](https://web.archive.org/web/20070223075434/http://asdf.org/~fatphil/maths/illegal.html)

Aside from that, the _qrpff_ perl scripts that became t-shirts ([https://web.archive.org/web/20011221024307/http://www.copyle...](https://web.archive.org/web/20011221024307/http://www.copyleft.net/item.phtml?page=product_1174_front.phtml)) were another fun and illegal way to point out the stupidity of the DMCA. But they aren't so pretty ;)

</comment><comment><USER107> This grammar of the aⁿbⁿ language in Prolog's Definite Clause Grammar syntactic sugar:

      s --> a,b.
      s --> a,s,b.
      a --> [a].
      b --> [b].

s is a non-terminal, a and b are preterminals, [a] and [b] are terminals and "\-->" can be read as "expands to". The syntax is the same as BNF and the grammar is a Prolog program that is directly executable as both a recogniser or a generator, depending on instantiation pattern at call time.

How does the grammar work? It must accept, or generate, a string of equal numbers of a's and b's, but the grammar is not keeping track of the length. There is nothing to count how many a's have been consumed or produced so far. _How does it know_?

s is the start symbol of the grammar. The first production of s, which is also the terminating condition for the recursion, accepts or produces one a followed by one b. The second production of s accepts an a, followed by an s-string, followed by a b.

Suppose we executed the grammar as a generator. In the first step, the output would be the string S₁ = ab. In the second step, the output would be the string S₂ = aS₁b. In the n'th step the output would be aSₙb.

So the grammar would always add exactly one a at the start, and one be at the end of its output, recursively.

And it would always generate the same number of a's as b's.

Similar for when it runs as an acceptor.

You can visualise the first couple of steps as follows:

               S
       ,</comment><comment>-|</comment><comment>-.
       |       S       |
       A      / \      B
       |     A   B     |
       a     |   |     b
             a   b

</comment><comment><USER108> [https://rosettacode.org/wiki/99_Bottles_of_Beer#World_model_...](https://rosettacode.org/wiki/99_Bottles_of_Beer#World_model_solution)

[https://en.wikipedia.org/wiki/The_Complexity_of_Songs](https://en.wikipedia.org/wiki/The_Complexity_of_Songs)

[https://en.wikipedia.org/wiki/Generative_music](https://en.wikipedia.org/wiki/Generative_music)

[https://en.wikipedia.org/wiki/Repetitive_song](https://en.wikipedia.org/wiki/Repetitive_song)

|><comment><<<

[https://en.wikipedia.org/wiki/E%3DMC2_(song)](https://en.wikipedia.org/wiki/E%3DMC2_\(song\))

[https://genius.com/Big-audio-dynamite-e-mc2-lyrics](https://genius.com/Big- audio-dynamite-e-mc2-lyrics)

[https://www.youtube.com/watch?v=cHTDkJ- bQqM](https://www.youtube.com/watch?v=cHTDkJ-bQqM)

</comment></comment><comment><USER109> The code for the "A Mind is born" 256 byte Demo. It produces quite a neat music sequence and visuals. The code doesn't have a code equivalent but the binary version is understandable. This post is 256 bytes. [https://linusakesson.net/scene/a-mind-is- born/](https://linusakesson.net/scene/a-mind-is-born/)

</comment><comment><USER110> As a student in 2001, Tim Sweeney's template recursive inheritance was next level for me:[https://www.flipcode.com/archives/Vector_Math_Quaternions.sh...](https://www.flipcode.com/archives/Vector_Math_Quaternions.shtml)

About 10 years later you would find this stuff everywhere in boost but for the time this was spectacularly elegant for C++

</comment><comment><USER111> One of the first recursive algorithms I learned was the solver for the Tower of Hanoi problem. I was stunned about its simplicity, solving a problem most people couldn't with just a few lines of code:

\- [https://en.wikipedia.org/wiki/Tower_of_Hanoi#Recursive_solut...](https://en.wikipedia.org/wiki/Tower_of_Hanoi#Recursive_solution)

</comment><comment><USER112> I once had to find all lines which did not contain a specific word. As back then i was absolutely new to regex stackoverflow came to the rescue - and i still have that link saved to this day - [https://stackoverflow.com/a/406408](https://stackoverflow.com/a/406408)

Regex for that is just great

      ^((?!word).)*$

</comment><comment><USER113> Das Inbox - an SMTP handler server written by Kenneth Reitz

[https://github.com/billzhong/inbox.py/blob/master/inbox.py](https://github.com/billzhong/inbox.py/blob/master/inbox.py)

It's about 42 lines of actual code excluding newlines.

</comment><comment><USER114>
      10 print "Hello World";
      20 goto 10;
      run

<comment><AUTHOR> My first language was QBASIC and much of the first code I read (other than modifying PHP scripts I didn't really understand) was from Pete's QB Site. I'd hardly call it beautiful, but definitely nostalgic and cool.

<comment><USER115> This is from QBASIC help file. Composing from PC speaker was very fun:

PLAY "MBT180o2P2P8L8GGGL2E-P24P8L8FFFL2D"

</comment></comment></comment><comment><USER116> [https://github.com/achael/eht-imaging](https://github.com/achael/eht-imaging)

This python code was part of the imaging, analysis, and simulation software for radio interferometry that led to the historical first 'image' of a black hole.

<comment><AUTHOR> What about the code did you find so striking? Any part in particular you recommend checking out?

<comment><USER116> Overall I refer to it as a good example of relatively complex - yet highly readable - python code.

It's utterly digestable due to its use of meaningful variable names, logical breakdown of functions and absence of 'clever' nontrivial one-liners.

</comment></comment></comment><comment><USER117> I like this bit of JavaScript for uniquifying an array:

      array.filter((item, index, arr) => arr.indexOf(item) === index)

It works because indexOf returns the index of the _first_ occurrence of the item, so you're asking whether this occurrence is the first occurrence.

<comment><USER118> Personally I like this one, although it only works for an array of primitive types.

        const unique = [...new Set(arr)];

<comment><USER117> The other advantage of the filter one is it can be stuck in the middle of a bunch of other list operations - map(), sort(), slice(), other filters(). Also, you can use findIndex() instead of indexOf() to match any arbitrary predicate, instead of exact equivalence.

<comment><USER118> Oh, for sure. I know .filter() has it's place, so if you need anything beyond making the array unique, I'd definitely use your solution.

The one I posted just blew my mind a little the first time I saw it, so I love to share it. I guess I never really considered spreading a set.

</comment></comment></comment></comment><comment><USER119> Easy: [http://hackage.haskell.org/package/recursion-188.8.131.52/docs/Co...](http://hackage.haskell.org/package/recursion-220.127.116.11/docs/Control- Recursion.html#v:zygo)

Also:

      subsets = filterM (pure [True, False])

</comment><comment><USER16> the recursive "find" function on a disjoint set forest with path compression, by R.E.Tarjan. It brings tears to my eyes every time I read it.

        int dsf_find(int *t, int a)
        {
         if (a != t[a])
          t[a] = dsf_find(t, t[a]);
         return t[a];
        }

</comment><comment><USER120> Quicksort in Haskell is very elegant, though not truly quicksort (not sort in place): [https://wiki.haskell.org/Introduction#Quicksort_in_Haskell](https://wiki.haskell.org/Introduction#Quicksort_in_Haskell)

<comment><AUTHOR> You are the second person to reference quicksort in Haskell in this thread. The other person even mentioned it not being true quicksort. Who knew quicksort in Haskell was such a beloved piece of code!

<comment><USER121> Back when HotOrNot was hot, there was a site like it for rating code snippets. The top-rated one, I think I remember, was a broken version of this sort function: it had left out the recursions or something (I don't remember exactly), which made it even more 'elegant'.

This wasn't the only case I noticed of highly-rated broken code there. It took me a long time to take this lesson to heart about especially slick-looking code of my _own_.

</comment></comment></comment><comment><USER122> Along these lines, does anyone else have the experience of reading some code and thinking "Damn this is good. So clear, so well formatted," only to realize moments later with a bit of embarrassment that it is your own code?

<comment><USER92> Or, worse, "who was the idiot that wrote this?"

... git blame ...

oh. me.

</comment></comment><comment> nils-m-holm Unification of the terms X and Y in the environment E in LISP (part of a PROLOG interpreter):

        (defun unify (x y e)
          (let ((x (look-up x e))
                (y (look-up y e)))
            (cond ((eq x y) e)
                  ((variable-p x) (cons (list x y) e))
                  ((variable-p y) (cons (list y x) e))
                  ((or (atom x) (atom y)) nil)
                  (#t (let ((ne (unify (car x) (car y) e)))
                        (and ne (unify (cdr x) (cdr y) ne)))))))

LOOK-UP looks up X or Y in E, VARIABLE-P returns truth, if X or Y is a variable.

</comment><comment><USER123> I have a T-shirt with this Perl code on the back: [https://www.perlmonks.org/?node_id=45213](https://www.perlmonks.org/?node_id=45213)

</comment><comment><USER124> Kinda seems like the perfect question to be used with this show hn from a couple days ago

[https://carbon.now.sh/](https://carbon.now.sh/)

</comment><comment><USER125> Curious why the comment about STL algorithms written by Alexander Stepanov was downvoted so hard it died? I'm not a C++ dev... is he hated or is the implementation that bad?

<comment><USER120> I was wondering too. His series of videos on YouTube from A9 on algorithms is excellent and has some very beautiful code but you have to work through the series to fully appreciate it.

</comment></comment><comment><USER126> Lazily-generated infinite list of Fibonacci numbers in Haskell:

        fibs = 0:1:zipWith (+) fibs (tail fibs)

Recursive definitions and lazy programming blew my mind.

<comment><USER127> And in Perl6 / Raku

my @fibs = 1, 1, * + * ... ∞

</comment></comment><comment><USER128> [https://github.com/seung- lab/dijkstra3d/blob/master/dijkstra...](https://github.com/seung- lab/dijkstra3d/blob/master/dijkstra3d.hpp#L240-L244)

      // Dijkstra, Edgar. "Go To Statement Considered Harmful".
      // Communications of the ACM. Vol. 11. No. 3 March 1968. pp. 147-148
      if (neighboridx == target) {
        goto OUTSIDE;
      }

</comment><comment><USER129> Here's one i'm really proud of, i crafted it when learning js a while back. Its a one liner that flattens arbitrarily nested array. Its recursive though, so i guess it has its limits. I remember commenting something along the lines of "dark magic functional prog" (thats how i found it a second ago in GH actually):

const flatten = arr => ((flat = [].concat(...arr)) => flat.some(Array.isArray) ? flatten(flat) : flat)()

Its simple, but i was - and still am - way to proud of it ;p

</comment><comment><USER130> For me: smr from 1995 ioccc, [http://www.ioccc.org/1994/smr.hint](http://www.ioccc.org/1994/smr.hint)

<comment><USER131> Lots of ioccc code are beautifully done. Especially the best self documenting ones.

</comment></comment><comment><USER132> From [1], a terse one-liner that outperformed many longer and more complicated entries in The Second International RoShamBo Programming Competition:

        int henny() {
          return((*opp_history?opp_history[random()%*opp_history+1]+1:random())%3);
        }

[1] [https://webdocs.cs.ualberta.ca/~darse/rsbpc.html](https://webdocs.cs.ualberta.ca/~darse/rsbpc.html)

</comment><comment><USER133> I always enjoyed reading Charles Petzold code on Microsoft Systems Journal.

When I discovered the Magazine (back un the 90's) I wasn't ready to code for windows nor win32 because I was a broke student with a 1MB 80286; but I am pretty sure reading and rereading that code and articles made me learn more C/C++ than most books or courses I took later.

Mr. Petzold: If we meet someday, the beers are on me!

</comment><comment><USER134> Recursive gem in PDP-11 assembler: convert binary value in R0 into ASCII:-

      CNV10: MOV R0,-(SP)    ;Converts binary value
             CLR R0          ;in R0 to ASCII in buffer
      1$:    INC R0          ;pointed to R1
             SUB #10.,@SP
             BGE 1$
             ADD #72,@SP
             DEC R0
             BEQ 2$
             CALL CNV10
      2$:    MOVB (SP)+,(R1)+
             RETURN

</comment><comment><USER135> Kind of cheating because Kernighan literally labels it as beautiful. It's Rob Pike's implementation of Ken Thomson's regex matcher.

[https://www.cs.princeton.edu/courses/archive/spr09/cos333/be...](https://www.cs.princeton.edu/courses/archive/spr09/cos333/beautiful.html)

</comment><comment><USER136> Gregory Chaitin discusses elegance of programs in his book _The limits of mathematics_ , which is a very good read. I wrote a review almost ten years ago here: [https://p4bl0.net/shebang/the-limits-of- mathematics.html](https://p4bl0.net/shebang/the-limits-of-mathematics.html)

</comment><comment> alex-ant Had a case where I needed to update MySQL column's value if an incoming argument is less/greater than it without using functions or procedures.

This returns the greatest value (passed ? or max_value column):

      ?^((?^max_value)&-(?<max_value))

And for minimum:

      min_value^((?^min_value)&-(?<min_value))

</comment><comment><USER137> [https://www.cs.princeton.edu/courses/archive/spr09/cos333/be...](https://www.cs.princeton.edu/courses/archive/spr09/cos333/beautiful.html)

Something completely different: the Factor language, in the beginning.

<comment><USER138> The link goes to an article about Rob Pike's regular expression matcher (which is great BTW).

Looking for the "beginning" of the Factor language led me to this wonderful site about concatenative languages:

[https://concatenative.org/wiki/view/Concatenative%20language](https://concatenative.org/wiki/view/Concatenative%20language)

</comment></comment><comment><USER139> I personally really like ruby's Array because it lets you pass anything and you can iterate over it:

      Array(nil).map ...
      Array("string").each ...
      Array(["a", "b"]].select ...
      Array([]).reject ...
      ...

</comment><comment><USER140> for(int i=1;i<=10;i++){ doStuff(); }

Sounds trivial compared to the rest listed here, but for me it was just the first time I got a for loop to work in java.

Like, conceptually I knew programming was about getting machines to doStuff, but this was probably the first time I actually had a machine do something I asked of it directly. Well, that and Logo writer.

[https://twitter.com/dosnostalgic/status/726236764759842817](https://twitter.com/dosnostalgic/status/726236764759842817)

</comment><comment><USER141> The Lambda Calculus ([https://en.wikipedia.org/wiki/Lambda_calculus](https://en.wikipedia.org/wiki/Lambda_calculus)).

</comment><comment><USER142> For me it's a function that calculates factorial using iterators in Rust:

      fn factorial(i: u64) -> u64 {
          (1..=i).product()
      }

In almost every other language this code would look messy or use some terrible recursion.

For example in C it would look something like this:

      long factorial(int n)
      {
          int c;
          long result = 1;

          for (c = 1; c <= n; c++)
              result = result * c;

          return result;
      }

Or with recursion:

      long factorial(int n)
      {
          if (n == 0)
              return 1;
          else
              return(n * factorial(n-1));
      }

In any case, I thin Rust looks better in every way with its cleaner syntax.

<comment><USER143> > In almost every other language this code would look messy or use some > terrible recursion.

Nah, lots of other languages can do this.

Python:

        def factorial(i):
            return reduce(operator.mul, range(2, i+1), 1)

Ruby:

        def factorial(i)
            (2..i).reduce(1, :*)
        end

Haskell:

        factorial n = foldl (*) 1 [2..n]

<comment><USER26> For Python, we don't need to supply the optional initializer 1. And reduce resides in the functools namespace (much like mul is in operator). I assume we're not talking about that peculiar dialect of Python that is no longer supported a few months from now.

<comment><USER144> Not only that but in python 3.8, it can be written:

        def factorial(n):
            return math.prod(range(1,n+1))

<comment><USER26> Nice!

</comment></comment></comment></comment></comment><comment><USER145> This :

[http://www.literateprogramming.com/knuthweb.pdf](http://www.literateprogramming.com/knuthweb.pdf)

(actual "code" starts on section C)

</comment><comment><USER146> My favorite is this one-liner for generating the Fibonacci sequence in Haskell:

      fibonacci = 1 : 1 : [x + y | (x, y) <- zip fibonacci (tail fibonacci)]

</comment><comment><USER147> This is a very open ended question.

For me, lazy as I am, most recursive algorithms operating on binary trees are a thing of beauty. Post-order ones even more so.

</comment><comment><USER148> Well, it's a C macro in Apache Thrift code base [1]

#ifdef __GNUC__

#define TDB_LIKELY(val) (__builtin_expect((val), 1))

#define TDB_UNLIKELY(val) (__builtin_expect((val), 0))

#else

#define TDB_LIKELY(val) (val)

#define TDB_UNLIKELY(val) (val)

#endif

This code is beautiful when it deal with CPU cache-line effects to speed up your program.

[1] [https://github.com/apache/thrift/blob/647501693bd14256df8839...](https://github.com/apache/thrift/blob/647501693bd14256df8839c13cb03659bdee4202/lib/cpp/src/thrift/transport/TBufferTransports.h#L32-L33)

<comment><USER149> You seem to be referring to the arguably beautiful _effect_ of code.

Are you seriously praising this monstrosity of preprocessor macros, integers used as magic booleans and compiler specific builtins as _beautiful code_??

</comment></comment><comment><USER150> This 4 instruction 8080/Z80 code sequence converts a 4-bit quantity in the A-register into the equivalent ASCII code: adc 40h

</comment><comment><USER73> I always liked the elegance of this definition of the power set function in Haskell:

      powerSet = filterM (const [True, False])

</comment><comment><USER151> Maybe not elegant but as a child, the first time I saw

repeat 360 [fd 1 rt 1]

used to draw a circle in Logo on the BBC micro. So obvious to an adult but blew my mind.

</comment><comment><USER152> For me it's gradient descent with back propagation and fast Fourier and fast multiplication Schönhage–Strassen algorithm.

</comment><comment><USER153> I did not write this, but:

      main(){char*s="main(){char*s=%c%s%c;printf(s,34,s,34);}";printf(s,34,s,34);}

</comment><comment><USER154> Personally, it is "hello world".

It is beautiful because it was my introduction to C that led to the world that I am in now.

</comment><comment><USER155> I've written several pieces of code that I am quite fond of. I guess the most recent was last year. A client asked what was necessary for a totally secure yet extensible blogging system. I ended up putting something together in Vue.js and AirTable that was tight, static, and extensible. That had a sweet feel to it. It was extremely small for having so many features. Fun times.

</comment><comment><USER156>
      class Universe(void):
          def __init__():
              eval("Fiat Lux")

</comment><comment><USER157> When I first saw something solved in a recursive way my mind was blown. Does that count?

</comment><comment><USER158> camel code: [https://www.perlmonks.org/?node_id=45213](https://www.perlmonks.org/?node_id=45213)

This was the first artistic use of code I had ever stumbled upon (not including LOGO programs).

</comment><comment><USER159> /bin/true on a v7 UNIX system. A zero byte file with the execute bit set.

<comment><USER159> Found a copy: [https://github.com/v7unix/v7unix/blob/master/v7/bin/true](https://github.com/v7unix/v7unix/blob/master/v7/bin/true)

</comment></comment><comment><USER160> select languageId, translate(language, languageId) language from language

it was a stored procedure to populate a dropdown list of languages each translated into their own language on an old asp.net app. i always liked it

</comment><comment><USER161> Doom Source. I don't do C, but this stuff just... made _sense_.

</comment><comment><USER162> TeX

<comment><USER163> FYI, there's an effort at the moment to translate XeTeX and dvipdfmx into Rust. Started with c2rust, now we have a test suite checking regressions against the entire arXiv archive. Contributors welcome. [https://github.com/crlf0710/tectonic](https://github.com/crlf0710/tectonic)

<comment><USER162> Why? It works fine. Does _everything_ need to be in Rust, or whatever the new language-of-the-day is?

</comment></comment></comment><comment> Iwan-Zotow Source of the original "true" command, presented to you below

</comment><comment><USER164> print("hello world")

This Python snippet is the most beautiful code I've read. It only went downhill from there.

</comment><comment><USER165>
        mv ax, 0013h
        int 10h

</comment><comment><USER166> print "Hello, World !"

Intro to pretty much any language. It opens up so many possibilities ..

</comment><comment><USER167> console.log('cellar door')

</comment><comment><USER168> d3js

</comment><comment><USER169> to count the unique lines from a file:

cat animals.txt | awk '{ cnts[$0] += 1 } END { for (v in cnts) print cnts[v], v }'

[https://blog.jpalardy.com/posts/alternative-to-sort- uniq-c/](https://blog.jpalardy.com/posts/alternative-to-sort-uniq-c/)

</comment><comment><USER169> awk '!seen[$0]++'

awk 'NR==FNR{A[$0]; next} $0 in A' file1.txt file2.txt

<comment><USER170> Thanks, was trying to remember that first trick just last week. For log files I had to make a slight adjustment to filter the time at the front:

      !seen[gensub($1, "", "g", $0)]++

For anyone wondering, it filters out duplicates by storing the first occurrence of the line and skipping subsequent ones.

</comment></comment><comment><USER171> comment bait

</comment><comment><USER172> I'll nominate this pseudocode from a paper of mine currently under review. Treat it like a koan to be meditated upon to gain enlightenment about AGI. The paper introduces an ordinal notation system in which ordinals are notated by computer programs. This pseudocode notates the ordinal omega^2. `, ⌜, and « are progressively higher-level opening quotation marks. ', ⌝, and » are the corresponding closing quotation marks.

LEFT = «X=⌜»;

RIGHT = «⌝; While(True) {Print(X); X=⌜Print(`⌝+X+⌜')⌝}»;

X = «Exit()»;

While(True) {

      X = LEFT + X + RIGHT;

      Print(X);

    }</comment>


'Error 53' fury mounts as Apple software update threatens to kill your iPhone 6 - <AUTHOR> http://www.theguardian.com/money/2016/feb/05/error-53-apple-iphone-software-update-handset-worthless-third-party-repair <comment><USER2> After hearing Apple's explanation, it sounds like a good idea (in theory) that they're disabling access to the phone and data. Otherwise, LEOs could confiscate your phone, have the home button / TouchID sensor replaced and potentially gain access to your data (let's assume you refused to unlock it for them).

However, Apple (and AASPs) should, upon request, replace the parts with "official" ones and restore access to the phone/data. I'm not saying they should do it for free but it should be offered.

The people affected by this error are getting screwed and it's not even their fault -- that's the worst part. Apple just saying "sorry, buy a new phone" will just have the effect of turning these customers away from Apple products.

<comment><USER3> No, that reasoning is not enough reason to brick a phone! They could at the most disable the whole Fingerprint system and delete any stored data. Or, restore the phone to factory settings after the update if they wanted to be extremely sure. Then the user could decide if the fingerprint sensor is worth getting the phone repaired by Apple at escalated costs.

<comment><USER4> Yeah, you'd think Apple could warn people first. They could perhpas issue an update that allows temporary unbricking assuming they care about their customers.

</comment></comment></comment><comment><USER5> Interesting but is there any good way around it? Apple needs to ensure the touch id sensor is valid. I mean perhaps they could simply display just touch id and nothing else (sounds like it does that at first but if you restart the phone it'll essentially kill the entire thing).

Seems like at the very least Apple could provide better error messages so their customers could understand why it's happening.</comment>


Codeigniter 4.0.0 final released today - <AUTHOR> https://github.com/codeigniter4/CodeIgniter4/releases/tag/4.0.0 <comment><AUTHOR> Finally Codeigniter release the most anticipated 4.0.0 version of his php framework. This is a new step forward for this community, after several years of incertancy and hard work. This is huge milestone for the team involved, congratulations to them.</comment>


Fresh Leak on US Spying: NSA Accessed Mexican President's Email - <AUTHOR> http://www.spiegel.de/international/world/nsa-hacked-email-account-of-mexican-president-a-928817.html

<comment><USER2>
        Commenting after TV Globo first revealed the NSA's
        surveillance of text messages, Peña Nieto stated that
        Obama had promised him to investigate the accusations and
        to punish those responsible, if it was found that misdeeds
        had taken place.

I would hope that any head of state would not be so naïve as to trust our current administration with respect to this issue. From most of my conversations, almost no one I talk to trusts them on the issue of surveillance.

</comment><comment><USER3> If you are top level government official and your mail is hacked by the NSA it is your fault.

I don't think that Snowden should have disclosed that kind of things. These are legitimate targets for SIGINT.

</comment><comment><USER4> _10 points by filipmaertens 1 hour ago | flag | 1 comment_

This is actually a reasonable article, but has been aparently flagged below the top 100 (currently, #105).

That was quick action by the thought police...!

<comment><USER5> Never mind that the same story was submitted over a month ago and discussed at considerable length:

[https://news.ycombinator.com/item?id=6315070](https://news.ycombinator.com/item?id=6315070)

<comment><USER6> The old article just had a few lines about this allegation, via an interview Greenwald gave to Brazilian media.

This Spiegel article, co-written by Laura Poitras, treads a lot of newer and deeper stuff:

> The National Security Agency (NSA) has a division for particularly difficult > missions. Called "Tailored Access Operations" (TAO), this department devises > special methods for special targets.

> That category includes surveillance of neighboring Mexico, and in May 2010, > the division reported its mission accomplished. A report classified as "top > secret" said: "TAO successfully exploited a key mail server in the Mexican > Presidencia domain within the Mexican Presidential network to gain first- > ever access to President Felipe Calderon's public email account."

> According to the NSA, this email domain was also used by cabinet members, > and contained "diplomatic, economic and leadership communications which > continue to provide insight into Mexico's political system and internal > stability." The president's office, the NSA reported, was now "a lucrative > source."

> This operation, dubbed "Flatliquid," is described in a document leaked by > whistleblower Edward Snowden, which SPIEGEL has now had the opportunity to > analyze.</comment></comment></comment>


Show HN: Volume Mixer for Mac - <AUTHOR> http://www.volumemixer-app.com/

<comment><USER2> Looks great. Now I need a tool to force certain apps to use certain output devices for those apps that don't let you select an output device independent of the default which would be 99% of them.

<comment><AUTHOR> That's a great idea. It'll take us a bit of time but we can put this place. Are you willing to help give us feedback as we design / implement this feature?

</comment></comment><comment><USER3> I have wanted this solution for years. Is it posable run Spotify out of speakers, but something else out of headphones?

<comment><AUTHOR> Using the builtin speakers while using the headphones at the same time you mean? That isn't possible. However, it is possible to send audio to say a bluetooth speaker and then other audio to the headphone.

</comment></comment><comment><USER4> Cool, looks nice!

Not related to the app, but the website. The main text above the app store buttons is really difficult to read, the contrast is quite low. Perhaps darken the text a little?

<comment><AUTHOR> What do you think now?

</comment></comment><comment><USER5> Not sure how good the developer(s) are at math. App store says $4.99 is 40% off. That would make the regular price about $8.33, which AFAIK, isn't allowed. ;)

<comment><AUTHOR> :) We had to round off to 4.99. The original price is 7.99.

<comment><USER5> I guess 38% off, though accurate, just doesn't have the same "zing" as 40% off :)

</comment></comment></comment><comment> Jean-Philipe One of the things many Linux desktop environments have built in and I need to pay for it on Mac. Besides that, nice app, just bought it.

<comment><AUTHOR> Thanks. If you have any issues, shoot me an email at mail{at}bibhas[dot]com.

</comment></comment><comment><USER6> Awesome, I've always wondered why I Apple never made a volume mixer! Maybe because Windows made it first ;). Thanks.

</comment><comment><USER7> The driver does not appear to be compatible with El Capitan yet.

Insta-purchased anyway because this feature was definitely needed.

<comment><AUTHOR> Have you been using VM? Is it working well for you? Got any feedback? Thank you :)

</comment></comment><comment><USER8> man I was thinking about this the other day. Love that windows has this built in, while all OS X get its a shake-to-maximize cursor that you can't turn off. :(

</comment><comment><USER9> Looks a nifty app. Quite missed this functionality that Windows 7 had.

However the site: Why is all html, content and styling in JavaScript? It's 2015, site should display something with JS disabled. And the HTML that is generated is awful.

Also, no fall back fonts specified, I'm on Windows and it appears not to have Lucida Grande installed. Times New Roman doesn't look as nice.

<comment><AUTHOR> I'll make these changes. Didn't have the funds to hire a web dev so had to hack it together myself. Thanks for the feedback.</comment></comment>


How books help us to be better human beings - <AUTHOR> http://www.newstatesman.com/culture/2015/08/how-books-help-us-be-better-human-beings

<comment><USER2> I thought I'd throw in a mention of a book on a similar topic, "The Shallows: What the Internet is Doing to our Brains", a Pulitzer Prize finalist in 2011:

[http://www.nicholascarr.com/?page_id=16](http://www.nicholascarr.com/?page_id=16)

If I had to summarize a few takeaways:

* Books are read in a linear fashion. Following a simple linear path helps us focus our attention on the content in a book and digest it. Reading cultivates habits of focusing and thinking deeply about a single topic.

* The internet is full of rich sources of information but is also full of distractions. People browsing the web simultaneously _digest content_ and _make decisions_ about how to navigate through that content, which distracts from the ability to absorb the content and form associations with it. Compared to book reading, web browsing also encourages quick-pleasure-seeking rather than focused, intentional, sustained attention that books help cultivate.

</comment><comment><USER3> _> In the late 20th century, however, there was a sustained assault from within the profession of literary studies on the very idea of common humanity_

I'm surprised someone at New Statesman admits this. Very often I feel that the very purpose of modern literary studies is to establish "credentials" that allow the holder to shut down discussion of books by using jargon and appeal to authority. In those disciplines, there is very little effort applied to improve the actual understanding of literature. Constructs, constructs, constructs. In the end, you end up spending most of your time dealing with linguistic constructs of the field itself and very little time thinking about the ideas of whatever author you study.

Noam Chomsky commented on this when speaking about post-structuralism. He noted that it's mostly an attempt to present "scientific" front for something that is inherently not a scientific field.

Of course, the response from the field was that he just doesn't understand what they're doing. Just like everyone else outside of the field.

<comment><USER4> I devoted a several years to studying continental / post-structuralist philosophy (Deleuze, Foucault, Derrida, Butler, Irigary, et al), and while I can't claim any authoritative knowledge I'd say I've at least done my homework, and I have to agree with Chomsky.

Post-structuralism essentially begins from the feeling that the rigor of modernism/structuralism is stuffy and oppressive. Post-structuralism's main project, then, is to deny the kind of stuffy rigor typical of the sciences any privileged position - that is, to deny that it is more correct than any other type of analysis. This is done through a variety of means, but you can find a good summary in [1]. The works in this area employ a dauntingly huge set of concepts that often serve as a barrier to entry and mystifier for outsiders. Science/mathematics is typically only donned to give a philosophers work an intimidating edifice to the non-mathematically inclined - see Badiou for a great example of this with set/category theory. Overall, it's a questionable project that seems to contribute little - see [2] for a good summary of this.

Overall, skip it if you can.

[1]: [http://philpapers.org/archive/SHATVO-2.pdf](http://philpapers.org/archive/SHATVO-2.pdf) [2]: [https://debate.uvm.edu/NFL/rostrumlib/SchwartzmanMar'00.pdf](https://debate.uvm.edu/NFL/rostrumlib/SchwartzmanMar'00.pdf)

</comment></comment><comment><USER5> I'm a better person for reading the books of Terry Pratchett, it was many years after I started reading them that I realised they have an implicit morality running through the whole series.

Honestly I don't know if I want to read his last as that has an air of finality to it.

<comment><USER6> I couldn't agree more with your statement. Pratchett was the best for me.

</comment></comment><comment><USER7> Reading a good book allows you to experience years of someone's life in just a few hours.

</comment><comment><USER8> > Conversation is the key: the problem with "academic" literary analysis is > that too often it sounds like talking at the reader or, worse, talking down > to him or her. And the style is all too frequently that of the monologue.

You don't say...

</comment><comment><USER9> Um, this article is bad. It takes a very long time to say not very much. I'm still not sure what the point is. I think that this article falls into the morass of 20th century literary/critical intellectualism whose primary occupation is navel gazing and recursive commentary based off of the original navel gazing. It's endless writing for the sake of name dropping.

Here is a good summary of this article: "Montaigne himself wrote a wonderful essay suggesting that the three best things in life are friendship, sex and reading, and the best of the three is reading. Your friend may die, your sexual partner may betray you, but literature is always there."

I fancy a good book quite frequently, myself-- books can allow themselves to be complicated or un-understandable and have niche appeal. That being said, this article seems to be contributing a bit to the "cult of books" which has become a bit more prominent in the recent years. Books aren't magical, and they don't always contain better information than other media. The main strength of books is their ability to go into depth and exist a long time.

Am I a better human being for reading a bunch of books? Probably, but the real self improvement comes from information transfer independent of source, not "books" intrinsically. Reading books just happens to be the fastest and densest information transfer from external world to brain, for me.

<comment><USER10> I think you miss the major points of the article. It is long if it is judged by the "standard" length of an article in a blogging era, and thus shorter attention spans of readers. It is not that long if one considers that the author was trying a topic that is hard to illuminate.

That doesn't mean it is a well-written article. Although he made his points clear, the writing could be better. I have read better articles on similar topics.

I think writing is a universal skill in terms that good writing can be applied to both literatures and technical books. The ways to convey one's points are usually quite different based on the topics. An imaginary example, an extreme one, is to write a novel in a way like writing a book on a programming language. Similarly, as readers, we can't expect the same reading experiences on Madame Bovary and Gang of Four.

<comment><USER11> > thus shorter attention spans of readers

Is there any actual evidence of this, or is it another _O Tempora, O Mores_ rant?

<comment><USER12> There is [http://www.telegraph.co.uk/news/science/science- news/1160731...](http://www.telegraph.co.uk/news/science/science- news/11607315/Humans-have-shorter-attention-span-than-goldfish-thanks-to- smartphones.html)

</comment></comment></comment></comment><comment><USER13> What exactly is a "better human being" ?

<comment><USER14> Good question! Using "better" for complex things without explicitly labeling the measurement axes is fluff ([https://xkcd.com/833/](https://xkcd.com/833/)).

<comment><USER15> Humanities is pretty much the embodiment of something that we could term subjective, no?

But having said that "better human being" was a term that came out of the age of enlightenment - intellectual, moral and physical growth were considered key. [1]

Hence books - with their ability to contribute on the moral and intellectual fronts - were always considered paramount.

Though with the fracturing of medial channels, books are just part of an ever larger mix. [1][https://en.wikipedia.org/wiki/Humanitas#Revival_in_18th_and_...](https://en.wikipedia.org/wiki/Humanitas#Revival_in_18th_and_19th_century_Germany)</comment></comment></comment>


RubyRescue - Your Ruby questions answered LIVE every Tuesday - <AUTHOR> http://rubyrescue.tv/ <comment><USER2> nice name...</comment>


Foreign companies in China handing over technology in exchange for market access - <AUTHOR> https://japantoday.com/category/tech/report-more-companies-in-china-handing-over-technology <comment><USER2> Great way to train your Chinese competition.</comment>