A lens is just a way to get and set a part of a data structure. Seems like a "why would anyone need this?" situation at first. However, they can be composed to provide shortcut access to deeply nested states. The main place I found this useful is in doing functional UIs. Because I end up with deep state hierarchy to represent UI pieces, consisting of both records and unions. Even if it was just records, updating a nested property is pretty gross with immutability. E.g.
Of course lens libraries exist to make it nicer to construct these with both get and set operations. However, I find I do not really use lens libraries. I usually just construct my own helper function "lenses" as needed.
Wow, thank you! This is really helpful. I've definitely run into nested property hell. I think you're right, I've been overthinking it. I'm pretty sure I could apply this pattern to a recent project of mine - practical use is the best way to learn it.
I really appreciate the examples!
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
A lens is just a way to get and set a part of a data structure. Seems like a "why would anyone need this?" situation at first. However, they can be composed to provide shortcut access to deeply nested states. The main place I found this useful is in doing functional UIs. Because I end up with deep state hierarchy to represent UI pieces, consisting of both records and unions. Even if it was just records, updating a nested property is pretty gross with immutability. E.g.
So if this is something you do a lot, you can construct a lens to simplify updating R. A lens has
get
andset
operations, but this is onlyset
.And you could even compose from other lenses. Here is a naive example of only the
set
part:Of course lens libraries exist to make it nicer to construct these with both
get
andset
operations. However, I find I do not really use lens libraries. I usually just construct my own helper function "lenses" as needed.Wow, thank you! This is really helpful. I've definitely run into nested property hell. I think you're right, I've been overthinking it. I'm pretty sure I could apply this pattern to a recent project of mine - practical use is the best way to learn it.
I really appreciate the examples!