Can anyone explain *what is lenses` in terms of OCaml?
I tried to google it, but almost all of them are in Haskell's world.
Just wish some simple demonstrations for it in OCaml's world, like what it is, what it can be used for, etc.
Can anyone explain *what is lenses` in terms of OCaml?
I tried to google it, but almost all of them are in Haskell's world.
Just wish some simple demonstrations for it in OCaml's world, like what it is, what it can be used for, etc.
A lens is a pair of functions (getter and setter) that are under a data-structure. It's really that simple. There is currently a library for them,
type ('s,'a) t =
{ get : 's -> 'a;
set : 'a -> 's -> 's; }
An example (using the ocaml library listed 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 a x -> {x with measurements = a}); }
let lens_measurements_inseam =
{ get = (fun x -> x.inseam);
set = (fun a x -> {x with inseam = a}); }
let lens_person_inseam =
compose lens_measurements_inseam lens_person_measurements
When composing the lenses together, you can see it as a way to avoid having to write with
constantly when dealing with records. You can also see that a ppx to create these lenses would be very helpful. Yaron recently posted on the caml-list they are working on something that would be similar to lens.
An important insight in the van Laarhoven Lens definition(PDF) shows how one function (fmap
) of a particular Functor can do these operations (set and get and very helpfully an update function).
set
imperative or functional? –
Beadroll 'a
, not unit
. –
Hurling © 2022 - 2024 — McMap. All rights reserved.