3 ms·
...what are lenses? Never heard of those.
by TwentyPosts 2y ago
...what are lenses? Never heard of those.
- turboponyy 2y agoAs with anything Haskell, one could simply reply with "here's the formal definition." But in easily digestible terms, it's a way to narrow your view over a collection to a subset that satisfies some property, and perhaps perform some operations on that subset. This video presentation (with a very humorous audience dynamic, might I add) serves as a great introduction by example: https://youtube.com/watch?v=QZy4Yml3LTY https://youtube.com/watch?v=QZy4Yml3LTY
- Zambyte 2y agoI'm going to watch the video, but I'm having trouble understanding how lenses are different from filter, and perhaps map. Is it just a combination of filter and map?
- matt-noonan 2y agoNo, it's quite different. A super rough but somewhat accurate starting point is to think of a lens as being like the `.foo.bar.baz` in `myobject.foo.bar.baz`: a way to describe some "location" inside of a data structure, in a way that allows for getting and setting. But lenses are also data, so they can be stored in variables, manipulated, and so on. It's a very useful concept, and very much not required or helpful when learning Haskell. It's also not a core Haskell concept in any sense, just something that has been built on top of Haskell as a library.
- lgas 2y agoAlso helpful to note that the "location" can be virtual. For example you could have a lens into the hours field a string that contains an ISO-8601 formatted date, so you could do something like let s = "20240722T193456.789-0800" putStrLn $ 19840206T193456.789-0800 -- prints "20240722T203456.789-0800" and they can be composed, so if you have some other lens that gets from your outer structure to an ISO-8601 formatted date string field, let's call that lens `fieldLens` then `fieldLens . hours` will get from your outer structure to the hours field of that date field.