【问题标题】:access a global reference list in ocaml [closed]访问 ocaml 中的全局参考列表 [关闭]
【发布时间】: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 refa :: b :: l 不会编译。
  • @Chris 那么在 OCaml 中甚至可以通过向列表附加新值来保存和更改列表吗?
  • 是的。 @Butanium 发布了一个答案,显示了 3 小时前的确切方法。确实建议您查看基本的 OCaml 教程。如果你被指示,补充它没有坏处。

标签: functional-programming reference global-variables ocaml


【解决方案1】:
l := a :: b :: !l;
(* Your code here *)

将完成这项工作。 l := foofoo 作为新值分配给l!l 访问存储在l 中的值

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    相关资源
    最近更新 更多