Display name
Display name

Reputation: 257

OCaml compiler expects an irrelevant custom type

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

In the code above, the line

"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 |"

throws an error of

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

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.

Upvotes: 1

Views: 95

Answers (1)

Display name
Display name

Reputation: 257

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) |

Upvotes: 1

Related Questions