101 points · by revskill · 3y ago · 81 comments
Its payoff doesn't seem to justify the cognitive overhead (concepts, operators, etc) that it brings.
I'd highly recommend that newcomers to Haskell avoid Lens in their own code for as long as possible. The juice really isn't worth the squeeze.
Lenses themselves are awesome. The "bad", naive, not-general type is really simple.
``` newtype Lens a b = Lens {get :: (a -> b), set :: (a -> b -> a)} ```
So simple that modifiers can be mechanically generated for your data types. And suddenly, you can express super-duper complex modifications without all the obnoxious boilerplate it'd otherwise take.
Say you have two data structures
data Struct1 = Struct1 { someStuff: [ Struct2 ] } data Struct2 = Struct2 { otherStuff: HM.HashMap Text Struct3 } data Struct3 = Struct3 { name: Text }
And you have a list `[Struct1]` and want a `[Text]` of the `names` of Struct3. How do you do this in an imperative language? Manually accessing the fields, for loops, etc.
The van Laarhoven formulation of lens and ekmett's lens library optiocs in Haskell makes this trivial.
`myList ^.. someStuff . each . otherStuff . each . name`
Now, what if you wanted to modify all the names and prefix them with 'id-'? Again.. trivial.
`myList # someStuff . each . otherStuff . each . name %~ ("id-" <>)`
Your formulation is just field accessors. Not composable, and ultimately no better than just using the generated field accessors haskell provides.
If you take Haskell and remove all the types (e.g. Scheme or JavaScript), you can have all the same abstractions, with basically the same syntax and operational behavior. But then of course the operational behavior is just applying/composing functions in the end... And because there are no higher-kinded types to deal with, category-theoretic language is less likely to sneak in.
I say this as someone who has used Haskell for years and studied category theory / PL theory as well. And I like all of those things, just think it's sometimes not really necessary to get the mental model at all and be able to use those tools.
I think that some code duplication is also not always the worst thing. Just because strings can be "combined" through concatenation and numbers can also be "combined" through addition does not necessarily mean you need one general notion/function to capture both, especially because if you take that to an extreme then you end up with some function that "sqoogles the byamyams" (i.e. the abstraction has become so general that the only way people really understand/use it is by looking at its concrete instantiations).
However, it was hardly ever used in practice because it isn't polymorphic and, perhaps more importantly, it can only be used for accessing a single item from a record.
The reason for the explosion of interest in "optical" libraries in the 2010s is because of the development of other optics that can simultaneous access multiple fields (in order), access a functor full of fields (unordered), access field that maybe doesn't exist, pattern match on a variant, zip an indexed set of fields, etc. And all of this is done is both a composable, and transparent way.
Haskell's Traversable functors existed in 2008, and while your lens type can also be traversed, you have to explicitly convert it to a traversable to use it and, or compose it that way.
I'm sorry you feel the need to understand profunctors in order to use optics. Ideally the system would abstract that all way. Unfortunately in Haskell, some of these components leak out (how much varies from implementation to implementation) because this abstraction uses constraints and polymorphism in a very novel way. It's kinda amazing that Haskell's type system accepts it at all.
The alternative seems to involve a proliferation of casting of optics upon every use, requiring either chaining of casts or writing n^2 casting functions from between every related pair of optics.
[0]https://web.archive.org/web/20071023064034/http://luqui.org/...
Based on the people who have amount of "C++ experts" I've interviewed over the years who don't know much about template metaprogramming or weird rules about initialization and class layout, yet have shipped meaningful code while avoiding most of the weird parts of the language.
Even languages like Python can get weird, such as default arg initialization:
def add_item_to_list(item, list_to_add=[]):
list_to_add.append(item)
return item
a = add_item_to_list(1)
a.append(3)
b = add_item_to_list(2)
What do `a` and `b` print?This is my go-to Python 1st-round question, and many prolific Python coders don't get through this.
From what little I've learned of Haskell so far, it seems like one can eschew the weird PL-heavy parts of the language and just be productive (with the tradeoffs the language contains, e.g. GC).
It seems to me that it's one of those things you've either encountered (and go "well, that's weird") or... haven't encountered (and go "well, that's weird" upon having it explained). Have pop quizzes about the sharp edges of various languages proved useful as a filtering mechanism?
a = add_item_to_list(1)
a.append(3)
b = add_item_to_list(2)
```Trick question it's a type error?
`struct ^. field1 . field2` to get stuff
and
`struct # field1 .~ blah` to set stuff.
It's syntactical memorization on par with any other language. A bit strange, but just syntax.
> The basic operators here are ^., .~, and %~. If you’re not a fan of funny-looking operators, Control.Lens provides more helpfully-named functions called view, set, and over (a.k.a. mapping); these three operators are just aliases for the named functions, respectively. For these exercises, we’ll be using the operators.
Everyone has their own tastes. Someone unfamiliar with the notation of ordinary algebra might argue for "you will have to find two numbers that the difference between the two is 10 (that is, so much as is our number) & that we make the product of these two quantities, the one multiplied by the other, exactly 1, that is, the cube of the third part of the variable" (https://www.maa.org/press/periodicals/convergence/how-tartag...) as easier to understand than "find u and v such that u - v = 10 and u v = 1", but I think most modern readers would agree that people uncomfortable with the algebra are better served by learning how to read the latter than by sticking with the former. (And, I think, also that it doesn't help either to keep the variables but replace the symbolic operations by words: `(and (eq (subtract u v) 10) (eq (mult u v) 1))`, in pseudo-Lisp.)
In contrast, most Haskell notation I've seen is either an ad-hoc invention for some library, or it is an ASCII version of notation in a niche domain like category theory. Even Haskell's >>= operator for flatMap/bind seems to be an invention, as far as I can tell the equivalent concept in CT is Kleisli composition, denoted by a sharp sign and the regular composition operator (as far as Wikipedia shows - I'm not formally trained in CT).
Additionally, people rarely if ever give a proper name to this notation in Haskell, making it completely impenetrable to even represent the formulas in your mind. How am I supposed to read `user1 ^. name` ? When I see `∇⨯f` I know how to read it (del cross f, or nabla cross f, or curl f) because that was an explicit part of how I was taught the operation (and note that it is not an arbitrary digraph, it can really be computed as the cross product of the pseudo-vector nabla and f), but Haskell tutorials and documentation completely skip this step, in my experience.
> In contrast, most Haskell notation I've seen is either an ad-hoc invention for some library, or it is an ASCII version of notation in a niche domain like category theory.
But that's my point! When it was introduced, none of the symbology of school algebra satisfied condition (1) or (2); it was ad hoc (perhaps supported by some reasoning—as Reade's for the equal sign being two parallel lines, "than which no two things are more equal"—or perhaps not), and was found fully as abstruse and obfuscatory as you find symbolic operators in Haskell. Even Arabic numerals were thought a device for lies and deception, compared to good honest Roman numerals, when first introduced.) If we hadn't adopted those operators anyway, then we'd still be writing out all our equations in words as Tartaglia did, and our mathematics would be the poorer for it; had we stopped our notation earlier, we would still, as in pre-Arabic numeral times, send our children to special advanced schools to learn multiplication. New notation when first introduced is confusing and strange, but, once made commonplace, enables new thought, so that what was a niche domain becomes commonplace.
(For that matter, I'd disagree about (2). For example, there is a symbol called the vinculum that is used for many purposes in mathematics (https://en.wikipedia.org/wiki/Vinculum_(symbol)). Probably almost everyone has used that symbol for one of its meanings, but I'd argue that very likely almost no-one knows its name.)
(Edit: I'd also be curious about `x += y` and `x << y` in C.)
(and (eq (subtract u v) 10) (eq (mult u v) 1)) could be:
(u `subtract` v `eq` 10) `and` (u `mult` v `eq` 1)
> (u `subtract` v `eq` 10) `and` (u `mult` v `eq` 1)
True. I used Lisp because I think it's reasonably common to use words for arithmetic operations in many Lisp dialects, but not in Haskell. But it's not the prefix notation to which I was objecting, but the idea of spelling out every operation when we've got a notation specifically designed to facilitate rapid thought and computation without that.
Optics don't just save you a few keystrokes. Instead, they make tedious code that you would never write trivial. And more importantly, they're composable. So it's impossible to appreciate their effectiveness without using them on a real-world app. For example, I've worked in an app with three layers, each with its record types, and without the lens library, the pain of converting between records would have been insufferable. Instead, most developers would couple the three layers together to avoid the problem, which makes the codebase brittle.
But I quickly ended up in dependency or type hell when I tried using them. I hope that people will take inspiration from the concept in the future.
Wouldn’t know about the dependency issues, but the newer ‘optics’ library [https://hackage.haskell.org/package/optics] has much simpler type signatures and greatly improved error messages. Personally I don’t like it, since it hides the implementation details too much for my taste, but it seems to be becoming pretty popular in the Haskell community.
A lot of the time when I couldn't completely untangle some type definition in lens library, I'd just go with gut feeling or guess what it does by analogy with stuff I already understood, and surprisingly often it compiled and worked like I expected.
I found Hoogle very useful for this guesswork.
You will need to attain a certain degree of fluency in Haskell before you have the problem that deep access into structures or any of the other problems lens can solve [1] is a clearly-separated problem that rates among your biggest.
Until you reach that point, I advise not to touch lens. By the time that is your biggest problem, it is likely that your other Haskell experiences will make it not too frightening, but it's not a very good gateway into Haskell.
[1]: One of my favorite uses, though not a common one, is that you can use it to abstract a pair (thing to operate on, how to operate on it) in a way where both the elements are still fully composable, where the lens is sitting in the second spot of that tuple, and whatever is operating on that only needs the type of the "how to operate on it" part, it is oblivious to the type of the "thing to operate on". I used it to build a game engine where the engine did not have a hard-coded concept of "player 1 goes, then player 2 goes, then player 1 goes", etc.; instead, the game logic itself decided that and all the engine got was a combination of what structs to manipulate and what to perform on that struct. (The engine itself did networking and converted things to and from JSON, while letting the pluggable game logic do everything else.) An interesting use for lenses beyond just "better record syntax" as I started passing the lenses themselves around in my code as first-class values. But probably ultimately an even worse way to get into Haskell than using lenses as record syntax improvements.... my point here is just that lenses do have uses beyond record accessing, that's just their headline usage.
No, this is not the true motivation. Human attention spans on symbols, the more succinct the code is, the more meaning it can encompass in the same number of characters. Writing abstracted enough code often requires inventing new languages to hide the complexity behind abstractions.
Software development in Haskell is particularly focused on DSLs, lens language being one of them.
^.. is a relatively simple operator though, it just abstracts away traversals.
Human attention may pick out symbols more easily, but human comprehension benefits from things that actually have meaning. Otherwise you end up with a soup of ASCII symbols that very few can parse since every library in Haskell seems hellbent on inventing new and useless ascii combinations for function names and operators.
Even the article goes (emphasis mine):
--- start quote ---
The basic operators here are ^., .~, and %~. If you’re not a fan of funny-looking operators, Control.Lens provides more helpfully-named functions called view, set, and over (a.k.a. mapping)
--- end quote ---
And then proceeds to use the ASCII soup instead of the more helpful function names.
It doesn't help in the least that there are multiple get operations ^. ^? ^.. Or this idiocy: "Here, a single < before the operator signifies that it returns the updated value, while a double << signifies that it returns the old value. This gets a little weird with the monoidal operator; <<>~ returns the updated value, not the old one". Bonus points. What does this do: <<<>~
Because "why have useful names when you can pretend your fake intellectual superiority by using confusing ascii symbol combinations"
> Software development in Haskell is particularly focused on DSLs, lens language being one of them.
The domain specific language for lenses is view, set, traverse, update etc. Not whatever this is.
The word you are looking for is "script"; though that is rather ambiguous in the context of programming. I suppose "writing system" is good enough.
And now we have entirely expressed the problem: someone tried to make their code more readable by adding a donation-specific writing system! Just break out your handy Rosetta stone, and you'll be fine, right?
I could make it even more succinct by LZW compressing it. That would not improve comprehension, though...
[EDIT] Nor do Perl libraries tend to contribute to or encourage line-noise style.
Perl is IMHO worse because it relies much more on global mutable context. For example, the diamond operator <> behaves differently depending on whether the magic global variable @ARGV is set.
By contrast, Haskell is typed and purely expression based, so that at least in principle you can pull apart expressions, examine them (and test them!) individually and then understand how they combine.
And Perl is not line noise. It's a very nice language.
But the language allows defining your own (infix) operators, so the core language designers weren't entirely innocent either. The abundance of custom operators in Haskell kind of made me appreciate Lisp and Forth a little more!
There are of course many good things about having your language designed by mathematicians, too.
> This isn’t meant as a lens tutorial. Prerequisites are some basic knowledge of how to use Haskell, GHCI, and familiarity of the idea of lenses, if not the specifics.
With that out of the way, it's kind of disappointing that the article isn't a tutorial. As it is, it just lists the lens operators, gives you alternate, but still non-obvious names for them, and foists some exercises upon you. It could have easily given one short example for each operator without adding any significant tedium for those who already have an idea of what they do, and then it would have been a perfectly fine tutorial.
So here's some examples, (Hoogle has some nice examples too; thanks Hoogle):
person = Person {_name = "Alice", _title = "Dr"}
-- get field with magic lens
person ^. title == "Dr"
-- create new object with new field value
person & name .~ "Bob"
== person & (name .~ "Bob")
== (name .~ "Bob") person
== Person {_name = "Bob", _title = "Dr"}
-- create new object with function applied to field value
person & name %~ lowercase
== (name %~ lowercase) person
== Person {_name = "alice", _title = "Dr"}