【问题标题】:OCaml User-Defined Type and Function Return ErrorOCaml 用户定义类型和函数返回错误
【发布时间】:2019-04-11 20:37:13
【问题描述】:

当我遇到我不理解的错误消息时,我正在 OCaml 中编写具有用户定义类型的函数。

我目前正在使用 OCaml 交互式顶层和 Visual Studio Code 来编写我的代码。奇怪的是,当我在 Visual Studio Code 中运行代码时,它编译正常,但在交互式顶层遇到错误。

我指的OCaml代码如下:

type loc = int;;
type id = string;;

type value =
  | Num of int
  | Bool of bool
  | Unit
  | Record of (id -> loc)
;;

type memory = (loc * value) list;;

exception NotInMemory;;

let rec memory_lookup : (memory * loc) -> value
= fun (mem, l) ->
  match mem with
  | [] -> raise NotInMemory
  | hd :: tl -> (match hd with
                 | (x, a) -> if x = l then a else (memory_lookup (tl, l))
                )
;;

我编写的代码基本上是我实现/模拟查找内存并返回相应值的初步尝试。


这是一个输入示例

memory1 = [ (1, Num 1) ; (2, Bool true) ; (3, Unit) ];;

这是预期的输出

memory_lookup (memory1, 2);;
- : value = Bool true

但是,这是实际输出

Characters: 179-180:
                 | (x, a) -> if x = l then "a" else (memory_lookup (tl, l)))
Error: This expression has type value/1076
       but an expression was expected of type value/1104

(只是为了澄清:错误是关于字符a


有人知道type value/1076type value/1104 是什么意思吗?另外,如果我写的代码有什么问题,谁能指出来?

谢谢。

【问题讨论】:

    标签: error-handling ocaml valueerror


    【解决方案1】:

    当一个类型被多次定义并且旧类型的一些值留在作用域中时,这种错误发生在顶层。一个简单的例子是

    type t = A
    let x = A;;
    type t = A
    let y = A;;
    x = y;;
    

    错误:此表达式的类型为 t/1012,但表达式应为类型 t/1009

    value/1076 中类型名称后面的数字部分是类型value 的绑定时间。此绑定时间用作区分碰巧具有相同名称的两种不同类型的最后手段。因此

    错误:此表达式的类型为 value/1076 但表达式应为 value/1104 类型

    表示值memory1 是使用在时间1076 定义的类型value 定义的,而函数memory_lookup 的类型为value 的预期值在以后定义(也就是时间@987654329) @)。绑定时间有点随意,所以在 OCaml 4.08 中可以简单地用 value/1value/2 替换。

    【讨论】:

      猜你喜欢
      • 2014-01-02
      • 1970-01-01
      • 2021-12-19
      • 1970-01-01
      • 2019-12-12
      • 2018-11-22
      • 2018-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多