3 ms·
The title needs to be changed, because: > This isn’t meant as a lens tutorial. Prerequisites are some basic knowledge of how to use Haskell, GHCI, and familiar
by SaddledBounding 4y ago
The title needs to be changed, because:
> 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"}