【问题标题】:Ocaml inference type int list instead 'a listOcaml 推理类型 int list 而不是 'a list
【发布时间】:2015-08-24 08:42:28
【问题描述】:
let rec getElement list index = match list with
| [] -> raise OutOfBoundException
| first::elems -> if index = 0 then first else getElement elems index-1;;

我不明白为什么这个函数的类型是 (int list -> int -> int) 而不是 ('a list -> int -> 'a)。 我需要编写返回列表中第 n 个元素的函数,它具有泛型类型(具有用户定义的类型 exp:http://pastebin.com/UefshcLa)。

如何编写该函数?为什么 Ocaml 推断该列表是 int list 而不是 'a list?

【问题讨论】:

  • 你也可以看看函数nth,它和你的函数做同样的工作。

标签: types ocaml type-inference


【解决方案1】:

OCaml 解释(getElement elems index) - 1,因为函数应用比-强。

let rec getElement list index = match list with
| [] -> raise OutOfBoundException
| first::elems -> if index = 0 then first else getElement elems (index-1);;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 2016-11-27
    • 2020-07-03
    • 1970-01-01
    相关资源
    最近更新 更多