17 ms·
Generalizing 'jq' and Traversal Systems using optics and standard monads
- benrbray 6y agoThis is a really exciting area. See also the Cambria project [1] and the HN discussion from yesterday [2]. See [3,4] for a great introduction to category theory for programmers--we are all indebted to Milewski / Fong / Spivak / et al. for making this topic more accessible. [1] https://www.inkandswitch.com/cambria.html https://www.inkandswitch.com/cambria.html [2] https://news.ycombinator.com/item?id=24699615 https://news.ycombinator.com/item?id=24699615 [3] https://bartoszmilewski.com/2014/10/28/category-theory-for-programmers-the-preface/ https://bartoszmilewski.com/2014/10/28/category-theory-for-p... [4] http://brendanfong.com/programmingcats.html http://brendanfong.com/programmingcats.html
- exdsq 6y agoWhenever I see Milewski’s name I immediately think of this video: https://youtu.be/ADqLBc1vFwI https://youtu.be/ADqLBc1vFwI It’s a shame I don’t know that many people who’d enjoy it as much as I do!
- rottc0dd 6y agoA great find. Thanks.
- 082349872349872 6y agoSo, how does Cambria differ from XSLT? For anyone interested in computing pre-history, early twentieth century punched-card processing, before von Neumann, was all about taking (monoidal) data structures (encoded as a deck of cards) with historical values and either querying them or running updates (encoded as a second deck of cards) to produce freshly copied current values. https://en.wikipedia.org/wiki/Unit_record_equipment https://en.wikipedia.org/wiki/Unit_record_equipment
- Daishiman 6y agoOptics, as the OP calls it, is definitely an underestimated problem of modern computing. So much work goes in most languages into processing nested data structures, especially in this day and age of heterogeneous APIs, and a lot of it is actually not that difficult to generalize conceptually into most languages. A few weeks ago I wrote a PoC in Python and it was remarkably easy to make a lens for traversing data structures. Declarative optics and updates would make writing business logic a lot easier on so many domains.
- warkdarrior 6y agoI wonder how these "optics" compare to .NET's Language Integrated Queries (LINQ) (see https://en.wikipedia.org/wiki/Language_Integrated_Query https://en.wikipedia.org/wiki/Language_Integrated_Query )
- Daishiman 6y agoLINQ is definitely a precursor, and has tons of fantastic ideas. It's unfortunate that Microsoft didn't continue to invest heavily into this as it's rarely mentioned nowadays.
- platz 6y agoI'm not sure I'd call LINQ a precursor when LINQ itself was based on haskell's monadic list comprehensions. monadic list comprehensions aren't quite the same thing as optics, however.
- formerly_proven 6y ago"Optics" and "lenses" seem like such bad names just to be able to make a "view data through a lens" pun.
- wwright 6y agoIt's not a pun, it's an analogy. When we want to see things in a different way in the real world, we literally use lenses (or more generally, optics).
- jkachmar 6y agoIt definitely can feel a bit strained at times, but the basic metaphor of: - lenses “focus” on elements of a product type - prisms “split” a sum type so that optics can work over selected branches ...feels nice when you’ve been working with it for awhile.
- whateveracct 6y agoThey're good names for a couple reasons 1. The analogies made do hint at their meanings. 2. But at the same time, the names are more proper nouns than definitions. For something so abstract, it's better to give it an opaque, easy-to-remember name than to give it a "better" name that maybe oversimplifies what it is. This is basically the "Functor" vs "Mappable" argument.
- formerly_proven 6y agoThey're practically useless for searching for them. Unsurprisingly trying to co-opt widely used terms tends to be ambiguous and confusing (cf. crypto <-> cryptography, cryptocurrency, and those are at least related). Perhaps the only exception in this group is "data lens", which works as a compound [1]. Guess what optics software does? No ETL, that's for sure. Optics patterns? Uh-oh. Optics development? Nuh-uh. Optics data? Turns out there are multiple companies with that name, and they're not doing ETL. Optics library? Image libraries of lenses (the kind you can touch). Optics computing? Sorry, that's a synonym of optical computing. Optics design? That's the engineering of optical systems. Optics scheme? Guess what arrangements of lenses are called... Optics programming? Aha, now the topic at hand actually manages to be in the majority of the results - barely, since four out of ten are still about that other thing humans have been at for a couple hundred years. Optics <programming language here>? Things for doing optical computations and simulations. [1] Also follows the rule of "if you're going to name something after a common word, maybe give it a qualifier not usually used with that word to make it unique and easy to find". Examples: sphinx (doc, search), click (cli), pyramid (web framework), pacman (linux), language (programming).
- vortico 6y agoWhy do you need all this theory when you can use simple imperative languages? for staff in company.staff: for pet in staff.pets: if pet.type == 'cat': print(pet.name + " belongs to " + staff.name) I don't understand why functional languages are used at all.
- mgraczyk 6y agoThat's more difficult to type than something like `.company.staff | .pets | flatten | filter .type == "cat" | log(...)`
- vortico 6y agoMaybe so, but much easier to read. Code is read 10x more often than written, especially in teams, so it makes sense to optimize for legibility rather than elegance in some "higher" mindset, or less keys pressed (because most of the time will be spent staring at the line you wrote than actually typing if you write a functional line like that.)
- kccqzy 6y agoThat's a bad argument because you didn't specify who the audience is. Functional code is more readable to me (and many teams I've worked with), imperative code is more readable to you and that's fine. Go with your team's preference. And, most of time, what your team prefers can easily be changed with a few sessions to introduce them to a functional style.
- akvadrako 6y agoI totally disagree. I can read the short version pretty quickly and get an idea what it does - every word matters. The original version with for loops just looks like a block of text. Spacing would help, but I would still need to look carefully to pick out the important bits.
- marta_morena_29 6y agoIt's a tradeoff. The problem is that academia often comes from the angle of abstracting and generalizing everything, which is even more harmful than copy & pasting and using the simplest code possible (mostly because copy & paste + simplest code is still readable and can be improved upon, while academic style code usually is inaccessible). You don't want to listen to any specific camp. The best is always in the middle and you are on the right track: "Pick what is easy to read." However there is a caveat, which is that functional style is only hard to read at the beginning. Have a look at how modern languages integrate functional programming (see java, C#, C++, etc.). Java streams are a common example. They make most code much easier to read ONCE you are used to it, because they provide standardized behaviour that is side-effect free. When you write everything in plain syntax, the reader needs to abstract your code in his head, while when using streams, you just know what `filter`, `map`, `reduce`, etc. do and you only need to look at the small customizations. It's easier to read once you are used to it. However there is a limit and this limit get hit quickly. A lot of people like to make their code as complicated and fancy as possible and reduce every possible line. This is definitely wrong. Code must be easy to understand and change. If you fail that, you are doing it wrong. This also depends on your environment. If your co-workers don't understand the code you write, you have failed, no matter if your code is "nicer" or not. You either need to write simpler code or educate your co-workers to create common ground.
- jadbox 6y agoWhat's the best optics library for typescript (or javascript)? Optika, partial.lenses, or other?
- carapace 6y agoNot CT (IIRC) but see also "Domain Modeling Made Functional" - Scott Wlaschin https://www.youtube.com/watch?v=Up7LcbGZFuo https://www.youtube.com/watch?v=Up7LcbGZFuo
- galkk 6y agoWhile I think it's closer to be dead on arrival (PartiQL), I like PartiQL/GoogleSQL way (generalizing SQL over nested structures) much more than the examples in the article
- ggm 6y agoless of the !
- d_t_w 6y agoWe recently implemented a subset of JQ in Clojure, converting filters and functions into Clojure predicates to allow our users to apply (K)JQ queries directly to Kafka topics holding JSON-like data (e.g Avro, Json, Transit, etc). If it's maps or vectors it works. The basic implementation is predicate composition as we support multiple combinations of filters. I hadn't thought any deeper about 'traversal systems' or optics, just parsing a grammar, creating predicates, and composing them. This is an interesting read, perhaps I should take the Clojure impl. further. https://www.youtube.com/watch?v=7krDIMjVzZM https://www.youtube.com/watch?v=7krDIMjVzZM Probably the most fun coding I've done this year because I had an excuse to use the wonderful Instaparse again.
- zaptheimpaler 6y agoSo overly complicated. The "state of the art" of FP now means heavy type systems and heavy machinery to deal with them. The 80/20 pareto of FP is just pure functions + composing those functions and it works in any language. Here is all of it in python: from __future__ import print_function import json struct = json.loads(open('staff.json','r').read()) staff = struct['staff'] salaries = struct['salaries'] def visit_pets(staff, cond, visit): for person in staff: for pet in person["pets"]: if (cond((person, pet))): visit((person, pet)) # Find all cats owned by any of our employees visit_pets(staff, lambda t: t[1]["type"] == "cat", lambda t: print(t[1])) # Find each pet and their owner visit_pets(staff, lambda t: True, lambda t: print("{} belongs to {}".format(t[1]["name"], t[0]["name"]))) # Give a $5 raise to anyone who owns a dog dog_owners = set() visit_pets(staff, lambda t: t[1]["type"] == "dog", lambda t: dog_owners.add(t[0]["id"])) for staff_id,salary in salaries.items(): if staff_id in dog_owners: salaries[staff_id] += 5 In my view it gets you 80% of the power of optics in exchange for zero machinery and can be understood by almost anyone. For doing these kinds of ops on a deeper structure, using Scala/Javascript or something with first-class support for HOFs, folds/filters/maps would work better. I wish more people promoted this view of FP - just pure functions, higher order functions and referential transparency. It gives you the ability to reason locally and extend code well. The remaining type system and architecture astronomy buys very little in relation to what it costs.
- one-punch 6y agoFor me, the remaining power of optics (what you call 20%): 1. let the compiler reason about my code to catch errors when the requirement changes (say, when some record fields change their names or types), 2. thus lower my cognitive load, and 3. allow me to reason about more important aspects of the project. At work, the use of a powerful and expressive type system allowed me to work on multiple projects at once, achieving at least 2 times boost in productivity (definitely more than 20% gain). Moreover, if optics is not well-known to everyone, I can just link to this blog post as a documentation, and give more examples if needed (I think people underestimate how coworkers could be productive without completely understanding everything). It is hard to explain the experience of “pair-programming with the compiler”, but such complication is worthwhile for the productivity gain (and developer happiness).
- spullara 6y agoThis guy is way better at jq than me.
- AnthonBerg 6y agoThe theory that describes what jq does and is proven to lead to further places is way better at jq than the implementation of jq that currently exists.
- spullara 6y agoi get it, i just grabbed an optics lib to use it.
- AnthonBerg 6y agoSincere apology, in joy too though: My previous comment was intended to be a joke-via-overdefinition but also constructive :) On reread it came out as kinda not-fun pedantry. Thanks for your understanding. I got your joke too :)
- toastal 6y agoI wish this blog were better optimized for mobile. I can't scroll back horizontally.