Lens: Lenses, Folds and Traversals

by hyperbraineron 7/1/2025, 12:08 PMwith 40 comments

by kccqzyon 7/4/2025, 2:41 PM

My biggest piece of advice for people using lenses is to ditch all the operators. Things like ^. or ^.. or ^? or ^@.. or even <<|>~ are all real operators. Yet they look like line noise. Nobody fully remembers them anyways. Just ditch all operators. Use named functions. The function toListOf is immediately clear what it's doing (that it takes a structure and a fold to convert to a list) but ^.. is not.

In general I avoid all custom operators and only use operators that are in packages preinstalled by the compiler (basically just base and containers).

by moominon 7/4/2025, 2:07 PM

Let’s just say that if you wanted to understand lenses, this is not where you should start; and if you wanted to move to more advanced scenarios, I wouldn’t start here either.

by haskmanon 7/4/2025, 4:33 PM

If you are looking for a more accessible introduction to lenses, this guide to optics in PureScript is great (and PureScript is basically Haskell). https://thomashoneyman.com/articles/practical-profunctor-len...

by eigenspaceon 7/4/2025, 5:52 PM

Julia actually has a very nice implementation of lenses in the Accessors.jl package: https://juliaobjects.github.io/Accessors.jl/dev/

I find it to be a lot more comprehensible and transparent than the Haskell version.

by 0_gravitason 7/4/2025, 9:23 PM

If you're in the Clojure world and feel an appetite for something like Optics, checkout the Specter library from RedPlanetLabs/Nathan Marz; it's Optics by another name, but functionally/philosophically quite similar.

https://github.com/redplanetlabs/specter

by srikon 7/4/2025, 9:03 PM

I learned lenses from the mentioned Edward Kmett video but wish I'd learned from the "Optics by Example" book instead; it's more cohesive, comprehensive and can save you a bunch of time - https://leanpub.com/optics-by-example/

by rrgokon 7/4/2025, 7:44 PM

I don't understand why Haskell can't provide an imperative interface (at the grammar level, not semantic level) to get/set values in a type. If you can provide the do-notation to "simulate" imperative code, then why not?

by johnfnon 7/4/2025, 8:46 PM

Everyone is like "Haskell is such a cool language, it's so much more clear concise and understandable than that stupid language you like so much" (their words, not mine). Then you ask them how they write `foo.bar.baz = 1` and you get 50k words of documentation, 113 new operators[1] like `<<<>~`, and a library with 20 new dependencies. I make fun of them only because I love them - I think Haskell has brought us a lot of cool things like Maybe and Either - but how has no one ever taken a step back and gone "wow, this seems a tad complex for what we're trying to accomplish"?

[1]: I'm not even exaggerating - https://hackage-content.haskell.org/package/lens-5.3.5/docs/...