OCaml sexplib,如何定义自定义的to_sexplib函数?

4

我正在使用 with sexp 语法来自动生成s-exp函数。

问题在于,我使用sexplib打印的数据结构具有一些递归指针,并且打印会导致堆栈溢出。

因此,我需要覆盖to_sexp函数,并使其返回"(SomeRecursiveData)",我该如何实现?

注意:我的数据定义的格式为:

type somedata ...
and someotherdata ...
and this_is_problematic_recursive_data
and ....
with sexp

1
你真的需要在同一定义中有 this_is_problematic_recursive_data 吗?或者它可以在之前定义吗?想法是在模块 Foo 中定义类型为 tthis_is_problematic_recursive_data ,并且在同一模块中定义 to_exp 。如果不可能的话,你应该考虑使用递归模块。 - Fabrice Le Fessant
@FabriceLeFessant,我不理解你的解决方案(我是OCaml的新手),但我认为模块无法帮助。我的问题是,我有一个ref列表,其中一个ref在运行时某个时刻指向列表本身。我想覆盖该数据类型(具有ref列表的那个)的to_sexp以防止这种情况发生。 - sinan
1个回答

1
我不能说我完全理解你的问题,但如果函数 to_sexp 不是交叉递归的(即 let rec to_sexp = ... 而不是 let rec to_sexp = ..... and foo = .... calls to_sexp somewhere.....),你可以尝试这个技巧:
module A = struct type t with sexp end

module B = struct 
  include A
  let to_sexp = .... your code ...
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接