如何更改记录中的部分值?
我定义了这样的类型:
type s_program =
{ globals : s_var list;
main: s_block; }
and s_var =
{ s_var_name: string;
s_var_type: s_type;
s_var_uniqueId: s_uniqueId }
and s_uniqueId = int
在我的程序中,我有一个变量 p: s_program
,但我需要更改 的每个元素的
将 s_var_uniqueId
例如,p.globals1
添加到每个 s_var_uniqueId
中。我有一些问题:
1) 我可以直接修改 p
中的相关值,还是必须将新值分配给新的 p':s_program
2) 我可以写这样的话:
let p' =
{ p with
globals = List.map (fun var -> { var with s_var_uniqueId = var.s_var_uniqueId + 1 }) p.globals
非常感谢。
编辑 1:按照建议更正 with
部分
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
1) 这取决于您是否想使用 Ocaml 作为命令式编程语言或函数式编程语言:)。如果是前者,您可以使记录的两个字段都可变(通过在字段名称前添加 mutable 关键字),然后就地更改它们。不过,我强烈建议不要这样做,并:
2)采用第二种方法,它看起来非常好(除了您似乎缺少第二个记录修改的
{...}
。1) That depends whether you want to use Ocaml as an imperative or functional programming language :). If it's the former, you can make both fields of the records mutable (by adding mutable keyword before field name) and then change them in place. However I'd strongly advice not to do that and to:
2) go with your second approach, which looks perfectly fine (except that you seem to be missing
{...}
for the second record modification.首先,您可能需要阅读记录在OCaml 和本章有关可修改数据结构。如前所述,您将看到记录是不可变的。其次,您需要考虑您真正想要的是什么:可变记录、具有可变字段的记录或具有可变字段的可变记录。例如,假设我们有一个复数记录(这与 参考 1)。
如果您声明类似的内容
,则您既不能更改
c
也不能更改re
(或im
)。事实上,c := {re=4.;im=6.} ;;
或c.re := 4.;;
都会因错误而失败。要获取可变记录,您只需使用c
的引用。然后您可以将
c
更改为c := {re=4.;im=6.} ;;
。但我认为你想要有可变的字段!然后你必须精确地确定哪些字段是可变的。假设您希望所有字段都是可变的,您可以编写然后更改字段,
使用
float ->; 类型的函数会更容易浮动-> ()
但是,我建议您认真考虑在代码中引入这样的命令式功能。这可能是一种完全破坏其可读性的简单方法。
First you may want to read this section on record in OCaml and this chapter on modifiable data structures. As stated, you will see that records are not mutable. Second, you need to think about what you really want : mutable record, record with mutable fields or mutable record with mutable fields. For example suppose that we have a record for complex numbers (this is the same example in ref 1).
If you declare something like
then you cannot change neither
c
norre
(orim
). Indeedc := {re=4.;im=6.} ;;
orc.re := 4.;;
will both failed with an error. To get a mutable record, you just have to use a reference forc
.Then you can change
c
withc := {re=4.;im=6.} ;;
. But I think that you want to have mutable field ! Then you have to precise which fields are mutables. Suppose that you want all fields to be mutable you can writeand then change fields with
It would be easier with a function of type
float -> float -> ()
However, I will suggest you to really think about bringing imperative feature like this in your code. This could be a simple way to completly wreck its readibility.