OCaml:自动执行自定义漂亮打印机的安装 [英] OCaml: Automate custom pretty-printer installing
问题描述
我已经为模块实现了漂亮的打印机.当前,我启动utop
,加载依赖项,然后执行#install_printer pp_custom;;
,其中pp_custom
是漂亮打印机.
I have implemented a pretty-printer for a module. Currently I start up utop
, load the dependencies then do #install_printer pp_custom;;
where pp_custom
is the pretty-printer.
我想使它自动化,以便可以用类似于lacaml
库的方式来使用它,其中默认情况下会安装"矩阵的漂亮打印机.
I would like to automate this so that I can have it in a way that is similar to the lacaml
library where the pretty-printer for the matrix is "installed" by default.
我该怎么做?
推荐答案
简而言之,只要在顶部加载库,就需要运行#install_printer
指令.我正在使用以下代码来评估顶级代码:
In short, you need to run #install_printer
directive whenever you load your library in the top. I'm using the following code to evaluate code in the toplevel:
open Core_kernel.Std
open Or_error
let eval_exn str =
let lexbuf = Lexing.from_string str in
let phrase = !Toploop.parse_toplevel_phrase lexbuf in
Toploop.execute_phrase false Format.err_formatter phrase
let eval str = try_with (fun () -> eval_exn str)
这取决于Core_kernel
,但是您可以通过使用eval_exn
而不是eval
轻松摆脱这一点(最后一个将可能的异常包装到Or_error
monad中).获得eval
函数后,即可用于加载打印机:
It depends on Core_kernel
, but you can get rid of this easily, by just using eval_exn
instead of eval
(the last one wraps a possible exception into the Or_error
monad). Once you've got the eval
function, it can be used to load your printers:
let () = eval (sprintf "#install_printer %s;;" printer)
其中,printer
是漂亮打印功能的名称(通常带有模块名称).通常,将这样的代码放入单独的名为library.top
的库中,其中library
是您的库的名称.
where printer
is the name of the pretty printing function (usually qualified with a module name). Usually, one put such code into the separate library, named library.top
, where library
is the name of your library.
要实现进一步的自动化,您可以要求所有想要在顶层自动打印的类型,将其自身注册到中央注册表中,然后调用所有已注册的打印机,而不用手工枚举它们.要一次查看所有这些工作,可以查看 BAP库.它具有一个名为bap.top
的子库,该子库会自动安装所有打印机.希望可打印的每种类型都使用 Printable.Make
来实现Printable
签名. functor,它不仅从基本定义派生许多打印功能,而且还在Core_kernel的Pretty_printer
注册表中注册生成的漂亮打印机(您可以使用自己的注册表,这只是一组字符串,仅此而已) ).将bap.top
库加载到顶层(使用require
或load
指令)时,它将枚举所有已注册的打印机和
For further automation, you can require all types, that you want to be auto-printable in toplevel, to register itself in a central registry, and then call all registered printers, instead of enumerating them by hand. To see all this working at once, you can take a look at the BAP library. It has a sublibrary called bap.top
that automatically installs all printers. Each type that is desired to be printable implements Printable
signature, using Printable.Make
functor, that not only derives many printing functions from the basic definition, but also registers the generated pretty-printers in Core_kernel's Pretty_printer
registry (you can use your own registry, this is just a set of strings, nothing more). When bap.top
library is loaded into the toplevel (using require
or load
directive), it enumerates all registered printers and install them.
这篇关于OCaml:自动执行自定义漂亮打印机的安装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!