[HN Gopher] Ask HN: What piece of code/codebase blew your mind w... ___________________________________________________________________ Ask HN: What piece of code/codebase blew your mind when you saw it? Mine was when I learned a subset of recursion called mutual recursion. It was for a pair of function to determine if a number was odd or even. (define (odd? x) (cond [(zero? x) #f] [else (even? (sub1 x))])) (define (even? x) (cond [(zero? x) #t] [else (odd? (sub1 x))])) Author : Decabytes Score : 84 points Date : 2022-10-31 21:06 UTC (1 hours ago) | jesse__ wrote: | Handmade Hero. | | Before warching Casey program, it had not occurred to me you | could sit down with a compiler and write an entire video game | from scratch. | | Then, I found out Jonathan Blow sat down and wrote his own | compiler, followed by an engine, and now has a game in flight. | | It's a truly incredible what these guys (and their teams) get | done. | cloogshicer wrote: | Hey, could you recommend an episode of Handmade Hero to get | started with? Should you just start at the very beginning or | somewhere later in the process? | gleenn wrote: | Reminds me of the author of the K programming language, Arthur | Whitney, wrote is own language, then database, and now he's | working on his own OS. | Isamu wrote: | Lots of good responses here, so I'll give an example that blew my | mind in a negative way: | | Fortran IV code, thousands of lines, no functions, only GOTOs | jumping everywhere randomly. Mostly one or two letter variables, | lots of GOTOs that turned out to be loops, with lots more jumping | into the middle of them and jumping out of them into other loops. | No documentation, I was supposed to modularize it. Failed. | | But it successfully calculated thermodynamic properties for | engineering designs, so go figure. | nanumbat wrote: | My first job in 1987 was porting all of Oracle's source code | (entirely in C for 32 bit architectures) to a 64 bit Control Data | mainframe. | | So, that. | eigenvalue wrote: | Was it particularly well written or optimized in very clever | ways? Bob Miner was supposedly a beast of a coder from what | I've read, so wouldn't surprise me. | _whiteCaps_ wrote: | https://en.wikipedia.org/wiki/Duff%27s_device | send(to, from, count) register short *to, *from; | register count; { register n = (count + 7) / 8; | switch (count % 8) { case 0: do { *to = *from++; | case 7: *to = *from++; case 6: *to = *from++; | case 5: *to = *from++; case 4: *to = *from++; | case 3: *to = *from++; case 2: *to = *from++; | case 1: *to = *from++; } while (--n > 0); | } } | vinay_ys wrote: | I encountered this technique and I learned the concept of | coroutines, it was quite something. | hansvm wrote: | I remember something about that too. Was this the blog you | read? | https://www.chiark.greenend.org.uk/~sgtatham/coroutines.html | krylon wrote: | For a long time, I would at this about once a year and _almost_ | understand what it does, but never quite getting it. It felt | like looking at a hypercube. | | Then I read it was about loop unrolling, and suddenly it | clicked. | omoikane wrote: | IOCCC taught me that form is just as important as function, and | often a lot more fun: | | https://www.ioccc.org/ | krylon wrote: | Years ago, fresh out of training, I got a job that involved image | recognition, and I spent a couple of weeks reading the code | dealing with image processing. I was confused, until I realized | that all the operations were basically the same, the only | difference was the matrix of weights applied to the pixels. | | That same week, I had a chat with a friend who at the time was | dabbling in audio processing, and we tried to understand how | lowpass and hipass filters worked. When we did understand it, I | realized they worked basically the same as the image processing | operations, just with a temporal aspect to it. | joshxyz wrote: | messagepack implementations. | | made me realize how much knobs are there in writing a data to | bytes encoding function.. you get to pick a trade off between | readability, ease of implementation (in other language), encoding | speed, encoding output size, and more. | nl wrote: | The Peter Norvig spellchecker: https://norvig.com/spell- | correct.html | | I like it because it's _so_ clearly coded - there are no crazy | syntax tricks or hacks - it 's just obviously the right way to | write it. And yet it is compact, elegant and non-obvious if you | are writing it yourself. | srik wrote: | CPS comes to mind (Continuation passing style). Apparently | continuations really do it for me. One of the many gains from | picking up functional programming is stumbling upon little | "pearls" like these that I wouldn't have otherwise. | | https://en.wikibooks.org/wiki/Haskell/Continuation_passing_s... | fferen wrote: | Data from functions: | | (define (cons x y) (lambda (m) (m x y))) | | (define (car z) (z (lambda (p q) p))) | | (define (cdr z) (z (lambda (p q) q))) | ihaveabeardnow wrote: | I once saw a 20k line Java source file, being used in | production... no it wasn't generated. that blew my mind. | marginalia_nu wrote: | Now that's job security! | pawelduda wrote: | More of a shell snippet, but removing duplicate lines with awk is | one that comes to my mind: | | awk '!seen[$0]++' | gorgoiler wrote: | Rob Pike's lexer was very nicely done and struck a chord with me. | It's not nearly as magical as some of the other things here. It's | just great engineering: | | https://m.youtube.com/watch?v=HxaD_trXwRE | gregfjohnson wrote: | Ken Thompson's self-perpetuating hack on the c compiler and | login.c to create a back door that is invisible in the compiler | source code and the source code of login.c. Described in his | Turing Award acceptance speech, "Reflections on Trusting Trust". | pyjarrett wrote: | C++'s "Curiously Recurring Template Pattern" | template <typename T> class Foo {}; class | Bar : public Foo<Bar> { ... }; | | https://en.cppreference.com/w/cpp/language/crtp | neeeeees wrote: | Good answer. OP didn't specify "blew your mind in a good way". | Turing_Machine wrote: | If "not in a good way" counts, my nominee would be | discovering the hard way that a Windows C function declared | as type BOOL can actually return 1,0, or -1. | | Now, if it had been declared int, I would probably have been | on the lookout for it using something other than 1 or 0 as an | error condition, but why bother to explicitly invent a BOOL | type and then abuse it that way? | skruger wrote: | Arthur Whitney's J Incunabulum: | https://code.jsoftware.com/wiki/Essays/Incunabulum | fegu wrote: | The doom square root trick. Reducing an expensive function to | almost nothing with low error. Many writeups on the web far | better than I could give. | jesse__ wrote: | I think you mean quakes fast inverse square root? Not aware | doom had a clever sqrt routine, but I would be happy to be | wrong! | kabr wrote: | *Quake | VirusNewbie wrote: | profunctor optics. | [deleted] | jiripospisil wrote: | Well, .NET's garbage collector certainly springs to mind. Not | exactly in a good way. You know you have something special on | your hands when GitHub refuses to show you a highlighted version | of a hand written C++ file (https://github.com/dotnet/runtime/blo | b/98984ccad55362a66b7fd...). | | Other than that, I remember my mind was blown a few times while | watching Jim Weirich's presentation on functional programming all | those years ago (https://www.youtube.com/watch?v=FITJMJjASUs). | btown wrote: | ICantBelieveItCanSort: https://arxiv.org/pdf/2110.01111.pdf | smcameron wrote: | Actually Portable Executables / Cosmopolitan | | https://justine.lol/ape.html https://github.com/jart/cosmopolitan | apeace wrote: | I really don't like that example. I get that it's just | demonstrating mutual recursion and not intended to be practical, | but I feel like there could be other ways to demonstrate that | concept that aren't so inefficient. | | My answer would be the jQuery code base, back in the day when | that was popular. At the time I didn't know a whole lot about | Javascript or the DOM. I remember it feeling like the kind of | code you could just read top to bottom and it was almost like | reading a novel. Really well-organized, well-commented, and | effective. I don't know if it's still like that, but at the time | it was transformative for me. | fegu wrote: | Swapping two variables without a temporary using xor. | nicklaf wrote: | Also: zeroing a register by XORing it with itself. | Turing_Machine wrote: | https://en.wikipedia.org/wiki/XOR_swap_algorithm | mjw1007 wrote: | Hashlife. | | I'm pretty sure that if something of the sort had occurred to me | before I came across it, I would have thought "that'll never | work" and moved on without taking it seriously. | nicklaf wrote: | Not programming per se, but: mathematical induction. It feels | like cheating to get an infinite number of true statements by | cleverly setting up a deductive argument. | jph wrote: | The Legendary Fast Inverse Square Root with "Voodoo Black Magic" | | https://medium.com/hard-mode/the-legendary-fast-inverse-squa... | jesse__ wrote: | 10/10 | KIFulgore wrote: | That one still kills me. By Carmack's comment, surprised him | too. | Phrodo_00 wrote: | The actual y combinator (for recursive anonymous functions) took | me a while to understand, and I'm pretty sure that by now I've | forgot how it works and would need to take a second look at it. | | On the less functional side, Linux linked lists are super smart. | gaudat wrote: | The Elixir |> (pipeline / nose) operator. Makes functional | programming much cleaner without brackets or intermediate | variables. I wish more programming language has this. JavaScript | comes close with chained calls of map. | swyx wrote: | it isn't rocket science, but | https://github.com/fkling/astexplorer significantly raised my | standard of what a readable, modifiable, nontrivial react/redux | codebase could look like. bonus that astexplorer is basically | used by everyone in the js tooling ecosystem | [deleted] | jeffreyrogers wrote: | Arthur Whitney's compiler for a language "isomorphic to c": | https://kparc.com/b/. | | Amazing that someone can write correct, fast code like that. | thenipper wrote: | Most legacy ML models I've had to move to production aka not on a | laptop. Oh you meant in a good way... | eb0la wrote: | A flight simulator called fly8 had an interesting C structure | made of pointers to functions. It was a way to declare a device | driver in C. | | Years later I could tell my colleagues how a device driver/plugin | actually worked (before COM/etc) just with this. | Phrodo_00 wrote: | uefi's boot services are pretty much implemented this exact | way. | tcgv wrote: | I was mind blown in college when learning recursive programming | and being introduced to the recursive solution to the Tower of | Hanoi problem: | | - https://en.wikipedia.org/wiki/Tower_of_Hanoi#Recursive_imple... | | I remeber thinking "where's the rest of the code? It surely can't | be just those lines!" | treffer wrote: | For codenbases... Objectweb ASM blew my mind. | | It's a library to read/write java class files. The core at that | time would fit into 2 java files. | | It was a reader and a writer built around a visitor pattern. At | that time apache bcel was also big, a library to build in-memory | class file representations which you would then manipulate. ASM | allowed you to do many transformation without ever holding the | whole file in memory. | | ASM also had an in-memory representation as an add-on. It was all | nicely layered and the core was just a marvelous small piece of | code, with incredible low memory consumption. | pierrec wrote: | I've read and re-implemented a lot of stuff by Inigo Quilez. Much | of it is ingenious but eventually straightforward once you get | the hang of it. I still find this particular snippet magical: | | https://www.shadertoy.com/view/MdB3Dw | | Well, the code itself is simple GLSL. The math is (and I have not | verified this) not that complex either, as I believe it's all | about integrating the raytracing equation for a moving sphere | over the time variable. I guess what I find most impressive is | just the fact that it works and that someone even thought of | doing that. I also think this is currently the only example of | this method being used anywhere, and it might mostly stay that | way because the method might not be super generalisable. | paulgb wrote: | His "Painting a Character with Maths" video is also incredibly | mind-blowing. | | https://www.youtube.com/watch?v=8--5LwHRhjk | CyborgCabbage wrote: | He has a YouTube channel as well: https://youtu.be/8--5LwHRhjk | | Also you may like Marble Marcher made by Code Parade, it's a | game that uses a similar approach to rendering: | https://youtu.be/9U0XVdvQwAI | jansan wrote: | Euclidean algorithm as a one-line function: | function gcd(a,b){ return b ? gcd(b, a%b) : a; } | racl101 wrote: | An oldie but a goodie. | davchana wrote: | Mine was super basic, one of many, that a 0 DAY can push an excel | date a day behind, so DATE(2022, 10, 0) means Last Day of | October. No need to keep an array of which month has 30, 31 or | 28/29 days. Simple DATE(2022,3,0) gives the last day of February. | Trufa wrote: | For me it was as simple as when I could start doing functional | programming with javascript. | | I was so surprised, since I had learned the other way first that | it is actually easier to teach functional approaches with | teenagers. | | arr.map(x => x _2) was abundantly clearer than | | const newArr = [] for(let i, i < arr.length, i++) { | newArr.push(arr[i]_2) } | | And to be perfectly honest, I might have goofed the for loop. | carl_dr wrote: | > I might have goofed the for loop. | | Yeah, you did! It should have used semi-colons. (And HN has | lost the carets ...) | | And I agree completely with you. | jansan wrote: | The javascript array functions and arrow functions are a gift | from heaven. | | _And to be perfectly honest, I might have goofed the for | loop._ | | You did, the commas must be semicolons :) | dopidopHN wrote: | I miss that ability to just pass whatever around easily in | JS. | | Ok... it's Footgun prone and callback hell is real. | | But I still try to obtain that in other more boring language. | mikercampbell wrote: | Functional JavaScript has saved me so much. And I'm not | talkin Ramda, just functional principles. | | I can't tell you how much time I spent chasing a bug when it | was a date that was passed by reference. | | Rather than trying to keep track, I just return copies of | arrays and objects and it's way easier. | | Even a simple | | ``` function yeppers(input) => ({...input, x: 7}) ``` | | (An overly simple example) | | has made things smoother. | joshxyz wrote: | this is a huge milestone in my coding. i remember refactoring a | bunch of my code as soon as i learned how to use map functions | lol | mattmiller wrote: | Its been a while since I worked with this lib but I always | thought Pygments was pretty. | | https://github.com/pygments/pygments | icelancer wrote: | A lot of VGA/SVGA paging blew my mind 20-25 years ago when I saw | it. | | Frankly, it still does. Low-mid level graphics code is incredible | wizardry. | downvotetruth wrote: | https://news.ycombinator.com/item?id=26607815 | fouronnes3 wrote: | In python the inverse of the zip function is zip. You call it | with with * to make list elements into function arguments. So a, | b = zip(*c) is the inverse of c = zip(a, b). | pklausler wrote: | Haskell: primes = filterPrime [2..] | where filterPrime (p:xs) = p : filterPrime [x | x <- xs, x `mod` | p /= 0] | KerrickStaley wrote: | This uses trial division to find primes, which is not | efficient, and I would not recommend using this implementation. | | Instead you should use the Sieve of Eratosthenes algorithm. | Unfortunately this algorithm is easier to implement in an | imperative, eager fashion than in a lazy, functional fashion. | | See the paper "The Genuine Sieve of Eratosthenes" for more | details: https://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf | [deleted] | mikercampbell wrote: | Haskell is one of those that I want to get into, but don't have | the bandwidth. I'm getting into elixir and even that has had to | require a shift of perspective ___________________________________________________________________ (page generated 2022-10-31 23:00 UTC)