ocaml - 在同一记录的其他字段中使用记录字段

标签 ocaml record mutable circular-reference

我想知道在 OCaml 中是否可以在同一记录的另一个字段中使用一个记录字段。

基本上,我有一个带函数的字段,我想在其中使用同一记录的其他值、字段,因此当值更改时,函数将使用新值。

我可以通过设置函数字段 mutable 并在创建记录后更新它来做到这一点,例如

type 'a cell =
  { mutable value: 'a
  ; mutable fn: unit -> 'a }

let create_cell ~(value : 'a) : 'a cell =
  let c = {value; fn= (fun () -> value + 42)} in
  let _ = c.fn <- (fun () -> c.value + 42) in
  c

我想知道如果 fn 字段不可变并且一次性完成是否有可能。

最佳答案

您可以使用 let rec 使函数引用它所属的记录:

# type 'a cell = { mutable value : 'a ; fn : unit -> 'a };;
type 'a cell = { mutable value : 'a; fn : unit -> 'a; }
# let rec r = { value = 14; fn = fun () -> r.value + 14 };;
val r : int cell = {value = 14; fn = <fun>}
# r.fn ();;
- : int = 28
# r.value <- 10;;
- : unit = ()
# r.fn ();;
- : int = 24

如果我没理解错的话,这就是你想要做的。

那么您的 create_cell 函数可能如下所示:

let create_cell ~(value : 'a) : 'a cell =
  let rec c = {value; fn= (fun () -> c.value + 42)} in
  c

它似乎有效:

# let mycell = create_cell ~value: 88;;
val mycell : int cell = {value = 88; fn = <fun>}
# mycell.fn ();;
- : int = 130
# mycell.value <- 100;;
- : unit = ()
# mycell.fn ();;
- : int = 142

关于ocaml - 在同一记录的其他字段中使用记录字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53060462/

相关文章:

types - ocaml 中的模块化编程

haskell - Objective-C 的跨平台函数式语言

multithreading - 当两个线程分别运行一个特定的进程时,一个线程返回值时程序会结束吗?

rust - 克隆一个 mut 引用以便在其他地方使用 mut 引用

ocaml 中的哈希表

arrays - 是否可能:记录中的数组

erlang - 定义记录,字段未定义

c++ - 如何获取给定单词所在的整行并将其存储在变量中?

redux - 在不改变状态的情况下修改 redux saga 中的选择器

pointers - 如何在 Rust 中传递对可变数据的引用?