OCaml中

问题描述:

下面的代码来自真实世界的OCaml第17章默认抱怨:数据序列化与S-表达式339页未编制上UTOP:OCaml中

type http_server_config = { web_root: string; 
port: int with default(80); 
addr: string with default("localhost"); 
} [@@deriving sexp] ;; 

据抱怨withport: int with default(80);

谢谢!

+3

这不是标准的[ocaml](http://caml.inria.fr/pub/docs/manual-ocaml/)。有一些额外的预处理涉及。 'default'不是一个Ocaml关键字。 –

在最近版本的Janestreet的Core库中,所有语法扩展名已从camlp4扩展名转换为ppx扩展名。因此,您不幸的是需要在Real World OCaml中使用语法扩展来调整所有示例的语法。

幸运的是,与camlp4扩展相反,ppx扩展不能疯狂地修改OCaml语法。与香草OCaml相比,它们至多可以使用稍微扩展的语法,并添加扩展节点和属性。

特别是,这意味着由于field:type with …对于vanilla OCaml不是合法有效的,所以它也不是启用ppx_sexp_conv扩展的有效语法。在你的情况下,默认值注释需要写成相应的记录字段的属性:

type http_server_config = { 
    web_root: string; 
    port: int [@default 80]; 
    addr: string [@default "localhost"]; 
} [@@deriving sexp] ;; 

注意的是,为了UTOP你首先需要有所需的 ppx_sexp_conv延伸和打开的默认工作在运行时模块:

#require "ppx_sexp_conv";; 
open Sexplib.Std ;; 
type http_server_config = { 
    web_root: string; 
    port: int [@default 80]; 
    addr: string [@default "localhost"]; 
} [@@deriving sexp] ;; 

Real World OCaml中的示例假定您已安装Core,其中包含一些语法扩展。我按照安装说明here,我仍然看到你遇到的同样的问题。

当我试图安装语法扩展模块,我看到这一点:

utop # #camlp4o;; 
utop was built without camlp4 support. 

所以,我断定这是一个有点棘手建立真实世界的OCaml的期待环境。

无论如何,@Basile_Starynkevitch是正确的。该代码使用的是您的utop不支持的语法扩展。