136 points · by self · 5y ago · 68 comments
I'll make a PR to try to contribute, instead of just complaining like that, hehe
Btw I'm surprised the structure isn't deeply nested (requiring recursion to process it), it'd be more interesting
It is something of a nit-picky argument to be sure, but it is a good mental habit to have.
Edit: I think being strict with the semantic building blocks is a good mental habit, not necessarily making nit-picky arguments.
You can argue that anything is nit-picky, under the guise of subverting good engineering in exchange for getting to be lazy.
The author of Specter goes so far as to label traversal/update of deep immutable structures as "Clojure's Missing Piece".
Basically the input is `data+config` merged into one object and the return value is `data+config+tranversal_properties` merged into one object with lots of solutions mutating the original input data.
I was expecting the FP languages solutions to be exceptionally short and elegant, but after a quick glance it seems to me that the Python and Python-like languages (e.g. Nim, Zig, etc.) are "winning" (YMMV of course).
The striking example is the JavaScript one: the simple imperative solution (for_of.js) is perfectly fine and lovely, but the other ones (map_with_state.js in particular) are total nightmares. Most of them are (almost certainly) significantly less performant than the simple imperative ones.
Not all problems are like this, of course, there are many examples where functional style code shines. But certainly there are many problems like this one, where imperative code is just the superior paradigm.
This is the case for 80% of real world code in IME.
The results and code might be rather individual preferences or ad-hoc solutions to typical problems. The data in the example does not require a lot of recursion to be elegantly processed. It is too simple an example for that.
The second aspect is, that the example code might have different priorities than the viewer. If I want to process a tree concurrently on multiple cores, then perhaps I should not be using much mutable state. However, if my priority is not concurrency and multi-core, then perhaps I can write it in very little code in Python and similar languages. When my priorities shift to concurrency and multi-core and lets say I got a deeply nested tree, I might have to adapt all these examples and suddenly the FP languages shine.
[0] https://twitter.com/josevalim/status/1379771275627921409?s=1...
For me the problem is too artificial to be meaningful.
The problem came from implementing a real feature into a course platform.
The data structure contains a list of sections and lessons to build a table of contents. The position stores the order they are being displayed in.
In the course viewing page lessons are annotated with a "#N" where N is the position and it goes from 1 all the way until the last lesson's count. This way folks could be watching the course and be like "Hey, I'm on lesson #56 and have a question".
But on the course description page the table of contents was displayed in such a way where the position / lesson count was reset for each section.
Although in the real life implementation this code is wrapped into a function and the reset_lesson_position is being supplied by a boolean function argument which controls whether or not the lesson's position gets reset for every section. We added it as an attribute to the section directly for the sake of this example to keep the problem more scoped to the core idea of the problem.
`resetLessonPosition` is not a member of the data structure but a parameter of the function that generates the positions and it has an effect on all sections.
Here's it being used in real code (search for "xpath_"):
https://github.com/libguestfs/virt-v2v/blob/master/v2v/parse...
https://github.com/libguestfs/virt-v2v/blob/master/v2v/parse...
Kinda ironic that given the problem definition no solution has been provided on XQuery or XSLT yet, the widely used domain specific languages that better suit the problem :-).
I believe there's a lot of inspiration to be had from the X-family of languages. The "secret sauce" is XPath. We need a new language drawing inspiration from the tree processing of X* languages but with more modern syntax and less with a less byzantine type system (read: anything but XML Schema :-). Less angle brackets would help too!
---
Bonus points: add tuples and prolog like queries to such language (thinking of SPARQL) ... now that would be something really powerful.
I won't deny that XML sucks to write. But I'm not yet ready to throw the baby out with the bathwater.
Maybe we keep using XML as a machine-readable serialization format (and XSLT as serialization of pattern-matching data transformations!) and people use native data structures in their own programming languages. Or we all switch to S-expressions.
Honestly, if XML had kept SGML-style implicit closing tags, we might have never seen the rise of alternative data markup systems.
That is, instead of
<foo>some_value</foo>
you should be able to write (as you can write in SGML) <foo>some_value</>
There. Now in exchange for a slight increase in parser complexity, you address a big syntactic wart (the repetition) the drives people away from XML. Seems like a win to me.I much prefer JSON, JSON Schema even JSON Path (although not used the latter quite as much as the first two).
Edit: XSLT could be kind of neat in some contexts if used with a degree of restraint, but it usually wasn't.
https://gist.github.com/raspasov/0521706c3f963a9209152bfb2be...
IMO The problem is poorly defined. Data structures should avoid control flow instructions like "reset_lesson_position"
Your "category" idea would be a nice addition to the problem though. The logic of when to reset would still be fairly simple and folks would have to explore how to represent the initial category value before traversal starts. I assume most would solve it with nil and maybe/option types.
It just feels nice to me.
Typical example: say you need to connect to an api that has pagination. You call it and you get a chunk which has a number of things and a counter of remaining chunks. Normally this king of thing requires the caller to keep a lot of messy state.
with yield you can make an interface that the caller can just iterate over and it will give them one thing at a time and fetch the next chunk if the current one is exhausted and there are chunks remaining. The state of the "current chunk", "chunks remaining", index etc can all be enclosed so the caller doesn't need to know anything about them.
But it doesn't prevent the caller from passing the handle to another function, or copying the handle, which could mess things up, and I suppose `yield` helps with that.
But most of all, I'd say it makes it easier to write the callee code, not the caller code, since the callee does not need to "reify" the state of "current chunk" and "chunks remaining" into an object, nor (more crucially) the state of loops and other control flow.
One of advantages of Perl to me stable syntax - usually I can open code written by someone nowadays after not using Perl and not encounter any unknown language features. Turned out even in Perl there are new features you need to learn first before you can read the code, though compare to other languages it still easy to keep up with all new features.
The biggest problem in Haskell that a language like JS doesn’t have is the types: you’re converting both the outer type for sections and the inner type for lessons into something else, so in any language with explicit static types you’re going to have the overhead of specifying those, or you have to hack around it a bit as we see here.
However, if you ignore the type boilerplate and the definition of the input data, the substance of the algorithm here would be around the same length as the imperative JS for-of version, particularly with less verbose names for the local variables as idiomatic Haskell tends to use.
With all four types explicitly defined and using another map-accumulate instead of the zipWith so updating the lessons with their positions was done similarly to updating the sections, I think it could be quite readable as well, even with Haskell’s limited support for record types.
[Edit: Having actually tried this now, even with DuplicateRecordFields, my Haskell code still seems unnecessarily verbose because of the record manipulations, but I still quite like the use of mapAccumL for making the pattern of computation explicit.]
[1] https://github.com/josevalim/nested-data-structure-traversal...
With that precedent, I'm happy to implement the given problem using State and traverse, so it's structured much the same as the obvious imperative version:
incr :: (MonadState s m, Num s) => m s
incr = get <* modify (+1)
annotate :: [Section x] -> [Section Int]
annotate ss = flip evalState 1 . forM (zip [1..] ss) $ \(i,Section title reset lessons _) -> do
when reset (put 1)
lessons <- (traverse . traverse) (const incr) lessons
pure $ Section title reset lessons ihttps://github.com/josevalim/nested-data-structure-traversal...
I personally often avoid long chained iterator operations, especially if they involve `for_each()`. Usually they're barely shorter than a for loop but seem to be harder to figure out for the type & ownership checker, leading to annoying issues with less helpful error messages. And just like with pipes in Bash I often run into situations where I wish I had multiple "channels" through which I can pass data, and a loop doesn't have any limitation like that.
Luckily there are multiple neat ways to solve problems in the language.
As noted in the message, I originally did this in elisp, which felt a bit more natural, for some reason.
> section.Object.get("reset_lesson_position").?.Bool
Also requiring the provide the type every time you retrieve an element from a JSON string again seems odd. JSON already has the data type, why do I need to provide the type every time I retrieve the data?
Because JSON is a serialization format, so as such it is external to your code. One day an element in the JSON you receive is a boolean, but another day it's a string, because another system had a bug and started producing junk data. Now in your code it's good to 1. document what type you expect, 2. trigger an error if the types don't match. It also has the benefit that all types can be checked statically, without providing any surrogate input. A schema integrated somehow with the language could be a more optimal solution though. But no schema, and no type annotations in the code is a no-no from me.
UPDATE: Now that I'm thinking about it, I'm wondering why JSON was used in the Zig example at all, instead of using builtin data types. Seems like a really odd choice.