首页 > 解决方案 > 什么是 TAPL 的 OCaml 实现中的模块、异常、FI 和 UNKNOWN?

问题描述

我正在阅读书籍类型和编程语言https://www.cis.upenn.edu/~bcpierce/tapl/)。

在它的第 4 章,算术表达式的 ML 实现中,它介绍了info. 我在这里下载了它的 ocaml 源代码arith.tar.gzhttps ://www.cis.upenn.edu/~bcpierce/tapl/checkers/ 。

这是开始support.ml

open Format

module Error = struct

exception Exit of int

type info = FI of string * int * int | UNKNOWN

我有几个问题:

第一季度

我在 MacOS 上安装了带有最新自制软件的 utop(版本 2.6.0),安装了带有opam install core base. 这是我的.ocamlinit

#use "topfind";;
#thread;;
#require "core.top";;

open Base;;
open Core;;

它给了我警报:

utop # open Format;;
Line 1, characters 5-11:
Alert deprecated: module Base.Format
[2016-09] this element comes from the stdlib distributed with OCaml.
[Base] doesn't export a [Format] module, although the
[Caml.Format.formatter] type is available (as [Formatter.t])
for interaction with other libraries.

utop # open Base.Format;;
Line 1, characters 5-16:
Alert deprecated: module Base.Format
[2016-09] this element comes from the stdlib distributed with OCaml.
[Base] doesn't export a [Format] module, although the
[Caml.Format.formatter] type is available (as [Formatter.t])
for interaction with other libraries.

什么是图书馆FormatBase.Format?我现在还需要打开它们吗?

第二季度

module Error = struct卡在 utop 解释器中。这条线是什么意思?为什么一直卡在utop?

第三季度

是什么exception Exit of int意思?

第四季度

什么是FIUNKNOWNtype info = FI of string * int * int | UNKNOWN

标签: typesocamlopamutop

解决方案


Q1:您应该使用Base.Caml.Format(或 Core.Caml.Format)而不是Base.Format(或仅删除基础/核心)。

Q2:我认为代码和缩进是错误的,这就是给你带来麻烦的原因,通常你定义一个这样的模块:

module M = struct
  type t = ...
  let f = ...
end

所以基本上, struct 是表示模块内容的开始。utop 希望您输入接下来的内容。

Q3:声明一个名为Exit的异常,它带有一个int,使用示例是:

exception Exit of int

let f () = raise (Exit 1)

let () =
  try
    f ()
  with
  | Exit n -> Format.printf "exit %d@." n

Q4:这是一个 sum 类型,由两个“case”组成,FI 和 UNKNOWN,第一个带有一个字符串和两个 int 使用示例:

type info =
  | FI of string * int * int
  | UNKNOWN

let print x =
  match x with
  | FI (s, i1, i2) -> Format.printf "FI (%s, %d, %d)" s i1 i2
  | UNKNOWN -> Format.printf "UNKNOWN"

let () =
  print (FI ("hello", 1, 2));
  print UNKNOWN

推荐阅读