【发布时间】:2022-01-13 18:18:05
【问题描述】:
我有这个代码:
let l = ref []
(*then I have this tail-recurse function
that is supposed to recalculate with a certain formula
all the values that are in the global reference list.*)
let f (a:int) (b:int) =
(*here I want to put the new values a and b in the
l - list and then do my calculations with all the contents
in l*)
所以也许有人可以通过示例向我展示如何做到这一点。
【问题讨论】:
-
你有没有尝试过?你有没有得到某种错误?假设您知道如何访问 ref 单元格和列表,我很难看出将它们组合起来会变得更具挑战性。
-
@glennsl 我做到了。使用
let f (a:int) (b:int) = a::b::l;; let rec sum = match l with |[]->0 |x::xs->x+sum;;但这似乎总是覆盖列表中的旧值。 -
记住
l不是int list。这是一个int list ref。a :: b :: l不会编译。 -
@Chris 那么在 OCaml 中甚至可以通过向列表附加新值来保存和更改列表吗?
-
是的。 @Butanium 发布了一个答案,显示了 3 小时前的确切方法。确实建议您查看基本的 OCaml 教程。如果你被指示,补充它没有坏处。
标签: functional-programming reference global-variables ocaml