OCaml 编译器需要一个不相关的自定义类型 [英] OCaml compiler expects an irrelevant custom type

查看:46
本文介绍了OCaml 编译器需要一个不相关的自定义类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

type int_tree =
  | IntLeaf
  | IntNode of int * int option * int_tree * int_tree * int_tree 

let empty_int_tree = IntLeaf

let rec int_insert x t = match t with
  IntLeaf -> (x, None, IntLeaf, IntLeaf, IntLeaf) |
  IntNode(a,None,c,d,e) -> if x<a then IntNode(x, Some a, c, d, e) else if x>a then IntNode(a, Some x, c, d, e) else t |
  IntNode(a, Some b, c, d, e) -> if x<a then IntNode(a, Some b, int_insert x c, d, e)
  else if x>a && x<b then IntNode(a, Some b, c, int_insert x d, e)
  else if x>b then IntNode(a,Some b, c, d, int_insert x e)
  else t

在上面的代码中,行

"IntNode(a,None,c,d,e) -> if x<a then IntNode(x, Some a, c, d, e) else if x>a then IntNode(a, Some x, c, d, e) else t |"

抛出错误

Error: This expression has type int_tree
       but an expression was expected of type
         int * 'a option * int_tree * int_tree * int_tree

带有下划线的 IntNode(x, Some a, c, d, e) 部分.这个表达式应该是 int_tree 类型,并且函数返回一个 int_tree,那么为什么编译器需要int * 'a option * int_tree * int_tree * int_tree"类型的东西?这甚至不是一种有意义的类型.如何阻止编译器将 a,b,c,d,e... 误解为泛型类型?通常你在 match 语句中编写类似 h::t 的东西是没有问题的,编译器知道 h 和 t 的含义.

with the portion IntNode(x, Some a, c, d, e) being underlined. This expression is of type int_tree as it should be, and the function returns an int_tree, so why does the compiler want something of type "int * 'a option * int_tree * int_tree * int_tree"? This isn't even a type that makes sense. How can I stop the compiler from misinterpreting a,b,c,d,e... as being generic types? Usually you have no problem writing something like h::t in a match statement with the compiler knowing what you mean by h and t.

推荐答案

事实证明,这个解决方案就在我眼皮底下.第一行是错误的.它期望与第一行的类型相同,解决方案是在那里添加 IntNode 以使其成为

Turns out the solution was right under my nose. The 1st line is wrong. It expected the same type as the 1st line and the solution is to add IntNode there to make it

IntLeaf -> IntNode(x, None, IntLeaf, IntLeaf, IntLeaf) |

这篇关于OCaml 编译器需要一个不相关的自定义类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆