在使用 ocaml
或 ghci
解释器时,我经常会建立一个重要的“上下文”(我没有更好的词来形容),包括绑定的值、函数、已加载的模块等。有没有一种方法可以将所有内容保存并在以后重新加载,以便我可以恢复到之前的状态?或者更好的是,将整个内容导出为文本文件,以便重新加载或轻松修改为编译成可执行文件的代码(例如通过添加一个 Main 函数)。
在使用 ocaml
或 ghci
解释器时,我经常会建立一个重要的“上下文”(我没有更好的词来形容),包括绑定的值、函数、已加载的模块等。有没有一种方法可以将所有内容保存并在以后重新加载,以便我可以恢复到之前的状态?或者更好的是,将整个内容导出为文本文件,以便重新加载或轻松修改为编译成可执行文件的代码(例如通过添加一个 Main 函数)。
至少在OCaml中,没有内置支持来实现这一点。一个解决方案是使用 rlwrap 或任何其他readline包装器将输入历史记录到文件中。例如:
> rlwrap -H mysession.ml ocaml
缺点是这样也会记录语法错误的输入,因此您需要清除它们。请注意,默认情况下,如果不使用-H选项调用它,rlwrap将自动将您的输入保存在~/.ocaml_history中。
:e 文件名
命令。这会打开标准编辑器并让您编辑某个文件。之后使用 :r
命令重新加载它。文件将被自动重新编译。ghci
使用haskeline来记录命令行输入历史,因此您可以向上滚动以重复/编辑输入。您的输入历史通常记录在一个文件中,您可以在给定目录中找到名为ghci_history
的文件。
System.Directory.getAppUserDataDirectory "ghc"
有各种命令可以探索“上下文”(:show bindings、:show modules、:def等),但它们的输出不足以重现您的会话(尽管了解它们也是值得的)。
一般来说,将您的ghci
会话与打开的编辑器窗口结合使用的建议很好:如果它不仅仅是一个丢弃的定义,即使只是为了调试目的,最好将其包含在一个模块中,以便可以将其重新使用到ghci
中。
哦,如果您所说的“上下文”是指每个项目基础上要加载的一些默认设置或模块,则还有ghci
的配置文件。也很方便定义自己的ghci
命令。
The ocamlmktop command builds OCaml toplevels that contain user code preloaded at start-up.
The ocamlmktop command takes as argument a set of .cmo and .cma files, and links them with the object files that implement the OCaml toplevel. The typical use is:
ocamlmktop -o mytoplevel foo.cmo bar.cmo gee.cmo
This creates the bytecode file mytoplevel, containing the OCaml toplevel system, plus the code from the three .cmo files. This toplevel is directly executable and is started by:
./mytoplevel
This enters a regular toplevel loop, except that the code from foo.cmo, bar.cmo and gee.cmo is already loaded in memory, just as if you had typed:
#load "foo.cmo";; #load "bar.cmo";; #load "gee.cmo";;
on entrance to the toplevel. The modules Foo, Bar and Gee are not opened, though; you still have to do
open Foo;;
yourself, if this is what you wish.
这个问题一直困扰着我,所以我写了一个快速的python/expect 脚本,在每个ghci会话开始时重新播放ghci_history。
它并不是很完美。例如,它总是重新播放整个历史记录,可能会很慢。