OCaml 世界中的 **lenses** 是什么
What is **lenses** in OCaml's world
谁能用 OCaml 解释 *什么是 lenses`?
我试过google它,但几乎所有的都在Haskell的世界里。
只希望在OCaml的世界里对它做一些简单的演示,比如它是什么,它有什么用等等
镜头是数据结构下的一对函数(getter和setter)。真的就这么简单。目前有一个 library 给他们,
type ('s,'a) t =
{ get : 's -> 'a;
set : 'a -> 's -> 's; }
裁缝的示例(使用上面列出的 ocaml 库),
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
将镜头组合在一起时,您可以将其视为一种避免在处理记录时必须不断编写 with
的方法。您还可以看到创建这些镜头的 ppx 会非常有帮助。 Yaron recently posted on the caml-list 他们正在研究类似于镜头的东西。
van Laarhoven Lens definition(PDF) 中的一个重要见解显示了特定 Functor 的一个函数 (fmap
) 如何执行这些操作(设置和获取以及非常有用的更新函数)。
谁能用 OCaml 解释 *什么是 lenses`?
我试过google它,但几乎所有的都在Haskell的世界里。
只希望在OCaml的世界里对它做一些简单的演示,比如它是什么,它有什么用等等
镜头是数据结构下的一对函数(getter和setter)。真的就这么简单。目前有一个 library 给他们,
type ('s,'a) t =
{ get : 's -> 'a;
set : 'a -> 's -> 's; }
裁缝的示例(使用上面列出的 ocaml 库),
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
将镜头组合在一起时,您可以将其视为一种避免在处理记录时必须不断编写 with
的方法。您还可以看到创建这些镜头的 ppx 会非常有帮助。 Yaron recently posted on the caml-list 他们正在研究类似于镜头的东西。
van Laarhoven Lens definition(PDF) 中的一个重要见解显示了特定 Functor 的一个函数 (fmap
) 如何执行这些操作(设置和获取以及非常有用的更新函数)。