gpt4 book ai didi

ocaml - 可变记录字段和 { x with ... }

转载 作者:行者123 更新时间:2023-12-03 16:56:17 27 4
gpt4 key购买 nike

我一直在阅读 ocaml文档,但我不能解释如何 { x with ... }围绕可变字段工作。 closest I've found

6.7 Expressions

expr := ...
∣ { expr with field = expr { ; field = expr } [;] }

...

Records

The expression { expr with field1 = expr1 ; … ; fieldn = exprn } builds a fresh record with fields field1 … fieldn equal to expr1 … exprn, and all other fields having the same value as in the record expr. In other terms, it returns a shallow copy of the record expr, except for the fields field1 … fieldn, which are initialized to expr1 … exprn.



“浅拷贝”的措辞可以解释为 mutable未提及的字段共享存储空间或可以引用嵌套记录。当我测试(使用“OCaml toplevel,版本4.00.1”)时
type t = { mutable x : int; mutable y: int }
let a = {x=42;y=123}
let b = { a with y=124}
let _ = a.x <- 43
let _ = Printf.printf "b.x=%d\n" b.x
;;

我得到的结果表明 b.x不别名 a.x :
b.x=42
type t = { mutable x : int; mutable y : int; }
val a : t = {x = 43; y = 123}
val b : t = {x = 42; y = 124}

这让我很高兴,但我想确保
{ e with fi=x }

是有效的语法糖,例如
(let tmp=e in { f0=tmp.f0; … fi-1=tmp.fi-1; fi=x; fi+1=tmp.fi+1; …; fn=tmp.fn })

还有那个 mutable字段不能由 ref 支持实现可以重用而不是分配新的可变存储。

最佳答案

在我所见过的任何地方,“浅拷贝”的意思是,就像通过赋值一样简单地转移所有组件,即使在所有字段总是可变的语言中,如 Java。所以在这种情况下 (let tmp=e in { f0=tmp.f0; … fi-1=tmp.fi-1; fi=x; fi+1=tmp.fi+1; …; fn=tmp.fn })正是它应该的意思。

关于ocaml - 可变记录字段和 { x with ... },我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13280224/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com