3 ms·
> Easier to build using imperative code than functional. I am a bit confused about this. The following code is pure and I can't think of an easier way to do it
by shhsshs 3y ago
> Easier to build using imperative code than functional.
I am a bit confused about this. The following code is pure and I can't think of an easier way to do it imperatively:
function triangle(n) {
if (n <= 1) {
return [1]
}
const p = triangle(n - 1)
return Array.from({ length: n })
.map((_, i) => (p[i - 1] ?? 0) + (p[i] ?? 0))
}
- taeric 3y agoI was actually mildly curious if anyone would call me on having picked an easy fractal to do with the recursion. :) When I wrote the post, I was thinking of the Koch curve. Not sure why I mixed it up in name with the other. I was definitely leaning on some of the abstractions that you get in the likes of turtle geometry to show how this works. Many of the programs you can write using those primitives are very interesting, and far more unwieldy in any other paradigm. At large, I view it as the difficulty of forcing Cartesian coordinates. For a large number of problems, things get far easier to state in polar coordinates. Such that your choice of abstraction and representation matters. A lot.
- PaulHoule 3y agoAnother "pure functional" approach to drawing these things is to write a shader program which takes the (x,y) coordinates and returns the pixel values. Here is a parameterized Koch curve done as a shader https://www.shadertoy.com/view/XdcGzH https://www.shadertoy.com/view/XdcGzH
- taeric 3y agoSadly, that page isn't loading for me. :( Mistake on my end? I'm going to guess that the shader version is a bit larger than the naive turtle version. Not that it isn't doable, but is tough evidence to hold for the benefits of the expressive power of functional code. :D
- PaulHoule 3y agoIt is 74 lines of basically C code on a page that runs the shader with WebGL. On my iPad it renders at 60 fps with a parameter that changes. It’s really neat. It doesn’t look like “functional code” but it really is since the shader returns a pixel color for x and y. I bet there is some squarish kind of fractal that could be code golfed with but manipulation.
- taeric 3y agoOdd that the page doesn't show me the code. For some reason, webgl is busted on my firefox at the moment. Not sure if that is my fault or something else. I'd expect it to still show the code, though. :( At any rate, thanks for the link! Will try another computer later to see if it can load.