I love lenses and other optics like prisms and folds, but only in a statically typed language like Haskell. It seems to me that it would be very hard to get things right in a dynamically typed language:<p>* First, it's possible that different elements of an array or different properties of an object has different shapes. I can't imagine how lenses can deal with that in an idiomatic way.<p>* Second, it's just difficult to get things right without a compiler's help. Forget a `traverse`? Now you are operating nonsense on the wrong level of your nested data structure. Trying to modify an inner structure but you only have a Fold instead of a Traversal? You won't know it won't work without running it to get some cryptic error.<p>* Furthermore, without types, we obscure the fact that setters and getters are unified: if `a` stands for the part and `s` for the whole, we just have<p><pre><code> (a -> f a) -> (s -> f s)
</code></pre>
that is, given a way to transform some inner part, we can transform the whole as well. Getters and setters are just supplying a concrete choice of f, namely the const functor and the identity functor. If we pick f to be the identity functor, then with some unwrapping we have<p><pre><code> (a -> a) -> (s -> s)
</code></pre>
so if there is a function that can modify the part, we have a function that can modify the whole by keeping the rest the same and modify that part. If we pick f to be the const functor, then with some unwrapping we have<p><pre><code> (a -> r) -> (s -> r)
</code></pre>
so if there is a function that can extract the value from the part, we can extract the value from the whole as well. Without types, this rather elegant unification of getter and setter seems to be lost.
In a language like C, the dot '.' and the arrow '->' are used for access into structures - both for setting and retrieving values. I think intuitively about a lens as a programmable dot which I can use to compose an access path. (You might have heard that the bind operator in a monad can be thought of as a programmable semicolon - this is similar.) This intuition might mean little if you haven't looked at lenses in more detail, but it does make sense once you have.
I recommend this post as well: <a href="https://medium.com/@gcanti/introduction-to-optics-lenses-and-prisms-3230e73bfcfe" rel="nofollow">https://medium.com/@gcanti/introduction-to-optics-lenses-and...</a><p>The author of the post is also the author of a TypeScript port of Monocle for Scala.
Has anyone done a performance analysis on the use of the lens concept in various languages? Given it is essentially duplicating data for every set it would seem to produce a lot of garbage for whatever memory allocator style is in use.
In C you don't need lens, either you set a member of a struct or you copy the struct and you set a member of the copy, trivial stuff. Why do you need a library for this kind of thing in Haskell?