【问题标题】:OCaml pattern matching type errorOCaml 模式匹配类型错误
【发布时间】:2016-01-17 00:48:16
【问题描述】:

我有这一段函数:

and interpret_read (id:string) (mem:memory)
               (inp:string list) (outp:string list)
: bool * memory * string list * string list =
  match inp with
  | [] -> raise (Failure "unexpected end of input")
  | head :: tail -> (true, (append mem (id, int_of_string head)), tail, outp)

内存类型定义如下:

type memory = (string * int) list;;

当我尝试#use 源代码时,我收到以下错误:

Error: This expression has type 'a * 'b
but an expression was epected of type (string * int) list

我还是 Ocaml 的新手,所以据我了解,'a 和 'b 是泛型类型,需要将它们定义为 string 和 int,然后才能将它们附加到 mem。我觉得这种理解并不完全准确,因为如果是这种情况,id 应该已经被定义为一个字符串,而 int_of_string 头应该是一个 int。谁能帮我解决我的困惑?

编辑: 我已将函数更改为以下内容:

and interpret_read (id:string) (mem:memory)
               (inp:string list) (outp:string list)
: bool * memory * string list * string list =
  match inp with
  | [] -> raise (Failure "unexpected end of input")
  | head :: tail -> (true, mem :: (id, int_of_string head), tail, outp)

我收到以下错误:

This expression has type memory = (string * int) list 
but an expression was expected of type string * int

这对我来说没有意义,因为它应该是内存类型。

如果我将函数更改为以下内容:

    and interpret_read (id:string) (mem:memory)
               (inp:string list) (outp:string list)
: bool * memory * string list * string list =
  match inp with
  | [] -> raise (Failure "unexpected end of input")
  | head :: tail -> (true, (id, int_of_string head), tail, outp)

然后我得到以下错误:

This expression has type 'a * 'b 
but an expression was expected of type memory = (string * int) list

这就是表达式的类型!这里肯定有我遗漏的东西,但我无法弄清楚。

【问题讨论】:

    标签: types pattern-matching ocaml


    【解决方案1】:

    您没有给出append 的定义。如果我假设这是List.append,那么它的类型是'a list -> 'a list -> 'a list。即,它需要两个列表并返回一个列表。但是您传递的是一个列表和一个元素(一对)。

    【讨论】:

    • 是的,对不起,它是附加的。那么我该如何追加一对呢?
    • 我想我会使用“::”?
    • 我对OP进行了修改,有时间请看一下
    • 是的,要将元素x 添加到列表xs 的开头,您可以编写x :: xs。您的第二次尝试首先是列表,然后是元素。您的最新代码只有元素,没有列表。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-05
    • 2013-06-14
    • 2021-12-13
    • 2018-08-19
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多