OCaml模式匹配类型错误

时间:2015-10-18 18:07:36

标签: types pattern-matching ocaml

我有一段功能:

// adds 99999 to each value
function bar(template, ...values) {
  var raw = template.raw;
  var result = raw[0];

  values.forEach((value, i) => {
     result += value + 99999;
     result += raw[i + 1];
  });

  return result;
}

console.log(bar`Test ${123}${'abc'}`); // 100122abc9999
console.log(bar`Test ${123 + 'abc'}`); // 123abc99999

内存类型定义如下:

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)

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

type memory = (string * int) list;;

我仍然是Ocaml的新手,因此我理解它' a和&b; b是通用类型,需要先将它们定义为string和int,然后才能将它们附加到mem。我觉得这种理解并不完全准确,因为如果是这种情况,id应该已经被定义为一个字符串而int_of_string head应该是一个int。任何人都可以帮我解决我的困惑吗?

编辑: 我已将功能更改为以下内容:

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

我收到以下错误:

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)

这就是表达式的类型!我在这里肯定缺少一些东西,但我无法弄清楚。

1 个答案:

答案 0 :(得分:1)

您没有为append提供定义。如果我认为这是List.append,则其类型为'a list -> 'a list -> 'a list。即,它需要两个列表并返回一个列表。但是你传递一个列表和一个元素(一对)。