What are ** lenses ** in the OCaml world

Can someone explain * what are lenses` in terms of OCaml?

I tried to do this, but almost all of them are in the Haskell world.

Just try some simple demos for him in the OCaml world, for example, what it is, what it can be used for, etc.

+6
source share
1 answer

A lens is a pair of functions (getter and setter) that are under the data structure. It's really that simple. There is currently a library for them,

type ('s,'a) t = { get : -> 'a; set : 'a -> -> 's; } 

Example (using the ocaml library above) for a tailor,

 type measurements = { inseam : float; } type person = { name : string; measurements : measurements; } let lens_person_measurements = { get = (fun x -> x.measurements); set = (fun ax -> {x with measurements = a}); } let lens_measurements_inseam = { get = (fun x -> x.inseam); set = (fun ax -> {x with inseam = a}); } let lens_person_inseam = compose lens_measurements_inseam lens_person_measurements 

When creating lenses together, you can see this as a way to avoid having to write with constantly when working with records. You can also see that ppx for creating these lenses will be very useful. Yaron, recently posted on a caml list , they are working on what would look like a lens.

An important understanding in the van Larhoven Lens definition (PDF) shows how one of the functions ( fmap ) of a particular Functor can do these operations (install and receive and very useful update function).

+8
source

Source: https://habr.com/ru/post/981620/


All Articles