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://floooh.github.io/tiny8bit/c64.html?input=${wait:200}...
Expressed in terms of line width (w) and number of lines (n).
[0] Where there's a valid path from the first line to the last.
Edited for clarity and accuracy.
/\/\/\/\
Also, I don't believe it doesn't depend on width. I think with constant height, the probability of completable one should increase with width, and become almost 1 for very large widths.But I wasn't treating /\ as an invalid on the first line. Eg thinking of:
/\/\/\/\
\\//////
/\\\\\\\ … and so on
(Using the /\ pattern, paths can go back up and come back down, so this requires a lot more thought than I instinctively put into it)What do you mean by that?
This is the art of illusion.
I was today years old when I learned this.
”Although early Cretan coins occasionally exhibit branching (multicursal) patterns
[…]
both logic and literary descriptions make it clear that the Minotaur was trapped in a complex branching maze
[…]
In English, the term labyrinth is generally synonymous with maze. As a result of the long history of unicursal representation of the mythological Labyrinth, however, many contemporary scholars and enthusiasts observe a distinction between the two.”
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.
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...
Name one person who perceives your comment as a maze.
It must be perceived as a maze by people for it to apply.
As it stands, I’m not sure if people perceive your comment as a maze.
Maybe theoretically there’s a nonzero number of people who perceive the comment as a maze. But unless your audience is those few people, there wouldn’t be much utility in it. In the OP’s example this maze perception is not only highly widespread but it’s also leveraged for a particular intended effect.
I'd suggest to not go bar-hopping in Thailand with that mindset...
First, you come blazing with accusations of transphobia, because of a joking mention of Thailand's ladyboy scene, to challenge the parents' notion that everything is WYSIWYG. Do you even know me? Or you have a hobby of randomly assuming things about people you don't know?
Second, when I don't take that quietly, you add the above comment about having the gal to defend myself, going for the "This animal is extremely vicious. When attacked, it defends itself" angle...
Perhaps you can go even lower against some stranger on the internet, but you wont be getting any replies from me in this thread.
* A person goes into a bar in Thailand, sees what they think is a girl and are surprised to find that things are not what they seem.
Broken down:
* Person sees a girl
* It is not a girl
* This is a bad thing
Now, it would be easy to claim (as indeed you and GP seem to be doing) that this isn't a slur on the second party in this encounter. It's a fact of the world. They exist. OP, the person who is saying that 'things are what they seem to be' would probably not want to find themselves in a situation where they making an assumption that the person is female.
The fact that this is negative can be seen in the 'I hope you don't' words which set the tone and are the basis of most of the sarcasm. I have to say that even if GP had picked a different example, I don't like this kind of comment anyway. It's a bitter, jabby comment that I don't think furthers discussion and overall makes HN a more negative and uncomfortable place to be.
So an assumption I made, which of course is debatable, is that the setting of 'bar' implies a romantic or sexual intent on the first party. GP will probably deny or refute this, but really without this implication there isn't much of a joke to speak of. "I spoke to this girl and it turned out she was a dude! What larks we had!".
GP seems to be making this claim in this comment:
>Nice to see confusing a joke reference to a regional fact (as to things that can seem X but be Y) with transphobia. Anybody told you that merely referencing trans women in Thailand is opposing them? Projecting much?
If it was 'merely referencing' then it wouldn't be a joke. 'Merely referencing' would we to reword the comment as:
"Things are not always what they seem, like commonly accepted phenomena of Thaiwanese ladyboys".
I mean, not much different, and still in poor taste for a thread that is about beautiful code, but the tone of the comment is completely changed. It's now no longer a jab at the PC, but using a counterexample to illustrate a point.
And why is suggesting that someone being shocked to discover a ladyboy transphobic anyway? Basically, it boils down to the fact that trans people have to suffer against stigma that they're somehow 'out to trick' people and that unassuming straight males need to 'watch out'. This comment is a prime example of this. It's literally a warning. Sure, it's mild transphobia, but it's perpetuating this stigma and I feel like Hackernews generally, and this thread specifically, are not really places for this kind of comment.
I normally wouldn't write this much out about this topic, but GP seemed very upset about their comment being called transphobic. Note, I didn't call them transphobic at all. I didn't actually make any comment about them, their person, their intent or anything. Just that the comment was 'casual transphobia' which I firmly believe that it is.
Let's break down the rest of their comment:
>Well, I am amazed that one can be so rude.
In both cases they use my own words back to me. I'm not sure why. It seems to be a mix of defensiveness and sarcasm. I don't actually think I was being rude - certainly no ruder than they were being to who they were commenting to. I felt that their original comment was snide.
>First, you come blazing with accusations of transphobia
I called the comment transphobic. Addressed above.
>to challenge the parents' notion that everything is WYSIWYG
Not very well.
>Do you even know me? Or you have a hobby of randomly assuming things about people you don't know?
This is incredibly defensive. Especially the second part. It's not enough to call out transphobia, they have to then pile on unfounded accusations of 'randomly assuming things about people' I don't know. I think the irony of this is amazing. They're literally accusing me of doing exactly what they're doing. It's like a bad girlfriend stereotype. (If you want to do some whataboutism, why not pick apart the inherent sexism of that comment? I'll give you a starter for 10 by lampshading it).
>econd, when I don't take that quietly, you add the above comment about having the gal to defend myself, going for the "This animal is extremely vicious. When attacked, it defends itself" angle...
So GP edited this comment a couple of times. Originally this was basically all there was. 'Having the gal' to defend themselves is a laugh. There was no self reflection, no admission that what they wrote could have been seen as transphobic. Just immediately jump to a victim paradox. 'Poor old me being attacked by nasty SJW just for merely mentioning ladyboys. Is it a crime? What did I do wrong????'
>Perhaps you can go even lower against some stranger on the internet, but you wont be getting any replies from me in this thread.
I mean I love this sign off. It's the reason I knew I had gotten to them and the reason I didn't reply. They didn't want to hear it. It was clear they weren't going to learn, and in fact they're telling me that they don't want a response anyway. I love the way that they're so deep in the role of the victim that they think I'm going to go off and harass more strangers. It's a lovely thought, but I don't do that. I just calls em as I sees em.
So anyway, I'm glad that you don't see the transphobia, but I don't think I was wrong to call them out on what I saw as implied transphobia.
perl -C -e 'print chr(9585.5+rand) while 1'
Wide character in print at -e line 1.binmode(STDOUT);
To the front.
Unicode on languages made before it existed is...argh.
I remember being fascinated with Pascal program that makes snow fall.
Basically, it was white dots on a blue background in an infinite loop. :)
I don't recall if it was one of the full issues, or one of the "insert issues" found within Family Computing of the era.
It was a special kind of "snow fall" generator; IIRC, there were only a couple of versions, one for the Apple IIe and the other for the PCjr - I likely used the PCjr version for the conversion since the BASIC language was nearly identical between the PCjr and my CoCo 2.
What was special was that it managed to seemingly move hundreds of pixels relatively rapidly on the screen; now, this might not seem like such a feat, but it really was considering we're talking about a computer system running an interpreted BASIC program, with a max speed below 1 MHz in standard mode (0.89 MHz - there was a so-called "speedup poke" that "doubled" the speed - POKE 65495,0 if anyone cares).
I don't recall what trick it used - or if it really used anything special at all - but I do remember being impressed by that bit of code.
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...
Having said that, it is elegant and clean and -- taken by itself -- does make Haskell very attractive.
But the flaw you note unfortunately undermines performance... the "quick" in "quicksort".
Thus, IMHO it's a compelling illustration of the profound strengths and weaknesses of fp.
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.
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.
Like to "recurse" (not actually recurse, but pretend) you would increment depth, the update the start position, and calculate the new partition index based on the (depth, start) tuple?
And run that in reverse for going back up the stack.
edit: Hah. This is fun. There's a variant where you do tricks with the elements of the array to get constant space.
https://link.springer.com/chapter/10.1007/BFb0016252
The idea is that you partition the elements, but then instead of storing the bounds of the left and right sides, you switch the element from the start of the right side with the partition element of the "stack frame" above you. This later serves as a flag indicating the end of the right side, since the partition of the parent "stack frame" is greater than all elements on the right you know you've hit then end of the right side when you see a larger number than the parent "stack frame"'s pivot.
Functional programming makes a different set of tradeoffs than imperative programming. You have to work harder to get peak performance, but in many cases it is actually quite performant. Just look at how fast Elm is for web applications, and how that approach allows for a time-traveling debugger and virtually no crashes.
If having to think a bit harder about your sorting algorithm is why functional programming sucks, can I give examples of every bullshit concurrency problem I’ve had in Java as an example of why imperative programming sucks?
Persistent data structures are a bit slower but largely become non issues if you deal with concurrency and avoid a lock that you would have otherwise required in C or Java.
It’s not like the people who wrote Haskell are idiots; most of these data structures end up sharing a lot of data, and a “new” structure is often only the diffs from the previous version. Not to mention that since you have a compile time guarantee that the data isn’t going to change, you effectively avoid any need for defensive copying.
I’m sure you can find some benchmark that proves C++ is faster in the most technical sense, but for network and multithreaded applications, it’s not even close; it’s so much easier to make sure a functional concurrent language is actually correct that the benchmarks become almost irrelevant.
The quicksort example is a shitty quicksort, because it will be slow as molasses. A proper quicksort in Haskell will degrade you to writing C in Haskell (with the benefits of a large standard library)and then you have lost. C in C will always beat C in Haskell or any other language.
Is it a worthwhile tradeoff? I believe so. The few times I am limited by speed in that way are few and far between, and most often it was because I thought something like O(n2) would be good enough which is easily fixable. Sometimes I just need to make optimal code faster. By then I always wish I would be using an imperative language instead.
Maybe your use-case is different than mine, but I typically use Haskell (or another functional language) for network applications, which typically don't benefit from tight-loops since the network is almost always the bottleneck anyway. For these kinds of applications, having proper concurrency and IO handling matters a lot more than worrying about whether your loops result in a cache-miss.
The lower level mucking around when you have to do those kinds of optimizations is, IMO, much more pleasant in imperative languages.
Also, have you tried Liquid Haskell? It uses refinement types to let you use the "unsafe" and fast versions of functions to guarantee correctness while also increasing performance.
Like everything else in life, those data structures come with tradeoffs. Accessing an array element is an indexing operation into a continuous block of memory. The indexing is built into the instruction set as an addressing mode, the array's memory is continuous (so better locality of reference for caching), and if you're traversing it predictably, prefetch hardware can being it into cache before you issue the instructions that do the read.
The same operation in a persistent vector is a function call, several pointer dereferences, and a more complex on-memory structure with more overhead. It works elegantly, but it's a completely different (and likely slower) level of abstraction from a simple in-memory vector.
A few years ago, I switched a toy search program away from ImmutableJS and over to naive copying of raw JS data structures. I don't remember the exact performance delta, but it was something like an x10-100 speedup, for code that was otherwise structurally identical:
https://github.com/mschaef/react-matchstick/commit/070802b69...
In this case, I had a goal to achieve, a timeline on which to achieve it, and it was the ability to switch to simpler, closer-to-the-metal data structures that made it happen. Had I needed more optimization, the most logical approach would have been to remove even more copying and rely even more heavily on mutation. This shouldn't come as a surprise, because at their core, these machines are fundamentally built on mutation, and there's a cost to pretending otherwise.
Now, in fairness to the persistent structures, this is something like a worst case scenario for their use - the algorithm is almost entirely dominated by manipulating relatively small data structures without much opportunity for sharing. It was also single threaded, small, and developed by a single developer in a small amount of time, so the organizational benefits of immutability were not apparent either.
If this was a huge redux state shared across a team of 100 developers and updated only a few times a second, I could probably tell a completely different story. It's easy to imagine (based on firsthand experience!) the kind of havoc that can be inflicted on a project with an erroneous update.
I get the enthusiasm for functional programming and persistant structures, etc., but at the end of the day it's just an engineering approach. One of many, and there's room to do the work to choose between them.
I don't disagree with this but that's not what you said initially. You said "this is why FP sucks".
I definitely think that if your work is doing tight-loops where every micro-second matters, an imperative language will usually be the correct approach. I don't think anyone is (or would) argue against that point, including most Haskellers.
However, functional languages do simplify things with network/concurrent applications. There's a reason that something like MapReduce is popular. Something like Spark or Onyx is just simpler to do correctly and work with than trying to achieve something equivalent using C or C++; maybe this is just me.
EDIT: My bad, I was responding to the wrong person, this person never said FP sucks. I apologize!
No, I did not.
That's why you shuffle the list before you sort it :)
It doesn't silently transform O(1) to O(n), the code is explicitly O(n^2) space worst-case. The only 'silent' transformation that could happen here is an optimization to improve performance. Also, I don't know where you got the 'enormous constant time overhead' part.
> Algorithms that are optimal under the mutable data assumption are different than algorithms that are optimal under the constant data assumption.
A normal programmer wouldn't be defining writing their own sort functions. A normal Haskell programmer would understand mutability in Haskell.
> Performant programming in Haskell requires a much more intimate understanding of the underlying architecture than performant programming in, for instance, C++.
It really depends on what you're writing and how much performance you actually need. Implementing a moderate-complexity parallel data processing algorithm in Haskell may result in a slightly slower but much simpler implementation than C++. An implementation of the same complexity in C++ may be slower than Haskell. Writing performant, parallel, safe code for a moderately complex algorithm in C++ is far from easy.
However, I get what you mean. It really is beautiful!
EDIT: grammar.
fibs = 0 : scanl (+) 1 fibs 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 .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.
I still remember my father ‘explaining’ me Pythagoras theorem when I was around 5 to show me how to draw the roof of a house on our hand-soldered Philips Apple II clone.
I’ve been hooked ever since.
The best thing was that 25 years later I opened a Logo emulator again and when faced with having to clean the screen somewhere deep, deep from my muscle memory the right command sprang forward: CLEAR
My father had installed Kubuntu on our home computer which had an amazing suite of educational applications, including KTurtle which was (almost) the same as PC Logo. I got so addicted to it, my father suggested me to create a blog and regularly update it with the drawings and the code for it. And so I did [1]! I used Google Blogpost (that was the thing back then). Good times :).
1: http://kturtlecommands.blogspot.com/
Edit: Just checked the blog after almost 6 years, it still gets 100+ weekly impression, haha :D
I recommend adding bookmarklets for Wayback Machine: https://en.wikipedia.org/wiki/Help:Using_the_Wayback_Machine...
CALL -151
That was the entry point to Apple 2's "monitor" (ie bare bones assembler). Not the most beautiful, but very evocative, gave me a sense of power :-)
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
Please do join it even if you don't remember Logo anymore. The intention here is not to discuss Logo but to share the joy of computing that we discovered through Logo and has remained in our lives. I hope to see you all there. :-)
By the way, there is also #fd100 channel on Freenode IRC but I am not sure whether most HN users prefer IRC or Slack.
"// what the fuck? "
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.
You mean inverse cube root? I believe the geometry ain’t easily upgradeable this way.
As the designer of the code, you would understand that the inverse square root is a standalone problem.
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.
It's a special case of 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.
What isn’t?
It didn't sound plausible to me (because I misunderstood what the algorithm was; yay perl), hence quickly testing it, but it seems to work, and after appreciating what the algorithm actually is (see sibling replies), it not only works but it _should_ work. (There is a CS versus engineering joke in here, somewhere.)
perl -ne '$x=$_ if rand()<=(1/$.); END { print $x }'But at least now I know that it's called Reservoir Sampling. I had wondered how to generalize it to wanting N lines.
(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.
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.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.
"I am in a REPL in a REPL in a REPL,
Running all my code in nested loops..."
I'm not saying the acronym came before or after the LISP code :P
(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=OyfBQmvr2Hchttps://github.com/webyrd/quines/blob/master/pmatch.scm
I have to agree, this like rank #1 in my book!
I was just recently (re-)reading an article that goes in depth:
Lisp as the Maxwell’s equations of software
http://www.michaelnielsen.org/ddi/lisp-as-the-maxwells-equat...
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!)
https://www.metalevel.at/lisprolog/ https://www.metalevel.at/lisprolog/lisprolog.pl
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.Then t would never be able to overflow s (nor even eat its null terminator)
The things you listed are general concerns in C which are unrelated to both the correct implementation and the suggested changes.
I wonder how much damage that code has caused.
This kind of code is cute, but awful for readability. The author could easily (more easily!) have written the function to be very readable, but went for the cute ultra-compact style instead.
The only reason it's at all readable is that it's solving such a simple problem. Write more complex functionality in that style, and you quickly get a nightmare.
I believe MISRA C outright bans this kind of thing (three assignments with no sequence point), as it has no place in a codebase of real consequence.
I understand that some C programmers pride themselves on being able to read this kind of code (far more impressive than being able to write it), but I see no reason for it in serious software work.
https://gist.github.com/zabirauf/29c89a084901cab8bc6b
Parsing binary data can be...nontrivial. The beauty is in the code that doesn't exist.
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.
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.
My current favorite is the one that dumped the SecureROM out of the iPhone 6 via PCI-e: http://ramtin-amin.fr/#nvmedma, http://ramtin-amin.fr/#nvmepcie
I'm partly impressed by the tooling used; most of the coolness (to me) is the author's self-confidence in his hunch that the SoC _didn't_ have its MMU set up properly, and the way he followed his nose in determining that he was probably right.
I still wonder exactly how much was sunk into the project, before it was possible to determine that the MMU was indeed broken. Heh.
It really inspired me to get better at seeking out the fundamental operations of whatever I was implementing.
https://github.com/chrislgarry/Apollo-11/blob/master/Luminar...
# HONI SOIT QUI MAL Y PENSE
and # NOLI SE TANGERE $ 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...
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.
I do, however, resent Python 3 for removing pattern matching on tuples in function heads.
> 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.
Unless you think compressed/ minified code is beautiful, there must be additional factors involved other than minimizing LoC.
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[0] https://unix.stackexchange.com/questions/419697/why-are-true...
Very elegant use of the fall-through behavior of the swtich statement.
Normal for-loops are much faster than they were when Duff's Device was invented, since they take advantage of modern branch prediction.
The Duff's device is still useful for creating co-routines though; a handy way of yielding, then returning to the yield point.
universal_server() ->
receive
{become, F} ->
F()
end.
[0] https://joearms.github.io/published/2013-11-21-My-favorite-e... :(){ :|:& };: %0|%0 $0|$0
on a file and running it should also work as a fork bomb. :( #sadface
:() #dopefish
{ : #smiling one-toothed vampire
{ :| #blank stare with hat
:| #blank stare without hat
|: #other blank stare without hat
|:& #blank stare with bow
}; #winking face with mustache
};: #winking four-eyed alien face with mustache
Only one of those was a smile, and you generally don't want a vampire smiling at you even if they're down a tooth! ;)Changed the way I think about code
Could you leave a sentence or two about how it made you "change the way [you] think about code"?
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.
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]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.
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 primes = sieve [2..]
sieve (p : xs) = p : sieve [x | x <− xs, x ‘mod‘ p > 0] class Derived : public Base<Derived>
[0] https://en.wikipedia.org/wiki/Curiously_recurring_template_p...https://zpbappi.com/curiously-recurring-template-pattern-in-...
#!/bin/rm#define EXIT_STATUS EXIT_FAILURE
#include "true.c"
[1] https://github.com/coreutils/coreutils/blob/master/src/true....
[2] https://github.com/coreutils/coreutils/blob/master/src/false...
10 PAUSE 4E4
"PAUSE nstops 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...
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.
_ = (
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... # 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" v = names[0] if names else "empty" d = {}
assert(d.get("blah"), None)
I was impressed by Rust the first time I run into: let mut last;
for i in &[1, 2, 3] {
last = i;
}
println!("{}", last);
>> borrow of possibly uninitialized variable: `last`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.
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.
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.- haskell:
perms [] = [[]]
perms xs = [ x:ps | x <- xs , ps <- perms ( xs\\[x] ) ]
- js: (using 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]))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.
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...
Red still has a little ways to go, but could be a game changer some day. The project is insanely ambitious, but I'm optimistic.
It's a bit like .NET Core. Great to base a business on... not so great to tinker around with. Arguably the second (tinkering, learning) comes before the first (using what you've learned to build a business).
Mildly infuriating...
Rebol 3 is open-sourced along with the GUI (R3-GUI)....
* https://github.com/rebol/rebol
* https://github.com/metaeducation/ren-c (community fork)
* https://github.com/zsx/r3-gui (Atronix fork)
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]
]
]Here's a Red version of the calculator: https://github.com/red/code/blob/master/Showcase/calculator.... 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/
If you liked Rebol, check us out, and help create the future.
>>>list(zip(*[(1, 2, 3), (4, 5, 6), (7, 8, 9)]))
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]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.
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.
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.
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...
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/...
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://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(&:+)Python: 2 * sum([x for x in range(1, 13)])
Haskell: 2 * sum [1..12]
GPs example is perfect Python; every character has meaning, and it's extremely readable even for non-programmers.
What’s so challenging about Ruby is how the language can be abused by library vendors to make all kinds of surprising magic and homegrown syntactic sugar.
Honestly, I don't think this has much to do with Ruby. This a consequence of using reduce or any other higher-order functions, which come from functional programming, and are now available in almost all modern multi-paradigm programming languages (including Python and Haskell).
I you like this kind of constructs, you should definitely learn a functional programming language, you'll love it.
2 * (1..12).reduce(&:+)
You could also use the closed summation formula: (n^2 + n) / 2. In our case that shortens to just 12*13=156. fibs = 0 : 1 : zipWith (+) fibs (tail fibs) ,[.,]
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 [
: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). : \ IMMEDIATE
#IB @ >IN !
; \ We can now comment!
Implementing a forth system is unbelievably fun because of gems like this.C (K&R) program that calculates PI number by measuring circle that is its code: https://en.wikipedia.org/wiki/International_Obfuscated_C_Cod...
Perl one-liner that checks if a number is prime: perl -lne '(1x$_) =~ /^1?$|^(11+?)\1+$/ || print "$_ is prime"'
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/~...Aside from that, the qrpff perl scripts that became t-shirts (https://web.archive.org/web/20011221024307/http://www.copyle...) were another fun and illegal way to point out the stupidity of the DMCA. But they aren't so pretty ;)
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
,-------|-------.
| S |
A / \ B
| A B |
a | | b
a bhttps://en.wikipedia.org/wiki/The_Complexity_of_Songs
https://en.wikipedia.org/wiki/Generative_music
https://en.wikipedia.org/wiki/Repetitive_song
|>~~~<<<
https://en.wikipedia.org/wiki/E%3DMC2_(song)
About 10 years later you would find this stuff everywhere in boost but for the time this was spectacularly elegant for C++
- https://en.wikipedia.org/wiki/Tower_of_Hanoi#Recursive_solut...
Regex for that is just great
^((?!word).)*$https://github.com/billzhong/inbox.py/blob/master/inbox.py
It's about 42 lines of actual code excluding newlines.
10 print "Hello World";
20 goto 10;
runPLAY "MBT180o2P2P8L8GGGL2E-P24P8L8FFFL2D"
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.
It's utterly digestable due to its use of meaningful variable names, logical breakdown of functions and absence of 'clever' nontrivial one-liners.
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.I try not to leave grenades laying around too often, myself.
const unique = [...new Set(arr)];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.
array.filter(Boolean)Also:
subsets = filterM (pure [True, False]) int dsf_find(int *t, int a)
{
if (a != t[a])
t[a] = dsf_find(t, t[a]);
return t[a];
}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.
... git blame ...
oh. me.
(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. fibs = 0:1:zipWith (+) fibs (tail fibs)
Recursive definitions and lazy programming blew my mind.my @fibs = 1, 1, * + * ... ∞
// 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;
}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
int henny() {
return((*opp_history?opp_history[random()%*opp_history+1]+1:random())%3);
}
[1] https://webdocs.cs.ualberta.ca/~darse/rsbpc.htmlWhen 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!
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)+
RETURNhttps://www.cs.princeton.edu/courses/archive/spr09/cos333/be...
This returns the greatest value (passed ? or max_value column):
?^((?^max_value)&-(?<max_value))
And for minimum: min_value^((?^min_value)&-(?<min_value))Something completely different: the Factor language, in the beginning.
Looking for the "beginning" of the Factor language led me to this wonderful site about concatenative languages:
https://concatenative.org/wiki/view/Concatenative%20language
Array(nil).map ...
Array(“string”).each ...
Array([“a”, “b”]].select ...
Array([]).reject ...
...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.
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.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] factorial n = product [1..n] def factorial(n):
return math.prod(range(1,n+1))Without the initializer, factorial(0) doesn't work.
But a more idiomatic C version would be
long factorial(int n)
{
long result = 1;
for (int c = 1; c <= n; c++)
result *= c;
return result;
}(defn factorial [n] (reduce *' (range 1 (inc n))))
Yet, since 20! is the last factorial representable in a u64, there is not much a point for these functions, and you should definitely check for n<21. It would be more elegant to store a lookup table with the 21 possible results.
In practice you would want the logarithm of the factorial, that is computed by the "lgamma" function from the C standard math.h. Is such a thing available in rust?
Edit: if you use doubles (which is more reasonable for that use case), you can also do that:
double factorial(double n) { return tgamma(1+n); } long factorial(int n) {
return n == 0 ? 1 : n * factorial(n - 1);
}http://www.literateprogramming.com/knuthweb.pdf
(actual "code" starts on section C)
fibonacci = 1 : 1 : [x + y | (x, y) <- zip fibonacci (tail fibonacci)]For me, lazy as I am, most recursive algorithms operating on binary trees are a thing of beauty. Post-order ones even more so.
#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...
Are you seriously praising this monstrosity of preprocessor macros, integers used as magic booleans and compiler specific builtins as beautiful code??
powerSet = filterM (const [True, False])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.
main(){char*s="main(){char*s=%c%s%c;printf(s,34,s,34);}";printf(s,34,s,34);}It is beautiful because it was my introduction to C that led to the world that I am in now.
class Universe(void):
def __init__():
eval("Fiat Lux")This was the first artistic use of code I had ever stumbled upon (not including LOGO programs).
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
This Python snippet is the most beautiful code I’ve read. It only went downhill from there.
mv ax, 0013h
int 10hIntro to pretty much any language. It opens up so many possibilities ..
cat animals.txt | awk '{ cnts[$0] += 1 } END { for (v in cnts) print cnts[v], v }'
awk 'NR==FNR{A[$0]; next} $0 in A' file1.txt file2.txt
!seen[gensub($1, "", "g", $0)]++
For anyone wondering, it filters out duplicates by storing the first occurrence of the line and skipping subsequent ones.LEFT = «X=⌜»;
RIGHT = «⌝; While(True) {Print(X); X=⌜Print(`⌝+X+⌜')⌝}»;
X = «Exit()»;
While(True) {
X = LEFT + X + RIGHT;
Print(X);
}