What is **lenses** in OCaml's world
Asked Answered
B

1

6

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.

Beadroll answered 27/1, 2015 at 18:16 Comment(2)
Are you talking about stuff like boomerang ? alliance.seas.upenn.edu/~harmonyBrentonbrentt
@Brentonbrentt no, i am talking about the lens thing in Haskell, but OCaml also has it. fpcomplete.com/school/to-infinity-and-beyond/pick-of-the-week/…Beadroll
H
8

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).

Hurling answered 28/1, 2015 at 17:8 Comment(4)
Is the set imperative or functional?Beadroll
functional, notice the function above returns 'a, not unit.Hurling
These were originally called functional references; that may help when searching for further information.Hurling
could you please add a simple example for demonstration?Beadroll

© 2022 - 2024 — McMap. All rights reserved.