Reputation: 911
I am new to OCaml and am trying to jump into a large OCaml project. While tracing through the types that make up other types I was trying to think how I would use these, so I broke it down to a small example that I think is pretty close to how it is in the larger project.
If I have the record type expression
made of three fields:
type expression = {e_id:int; e_node:exp_node; e_loc:location}
and exp_node =
| Const of int
| Lval of lval
| SizeofStr of string
and lval =
| Var of varinfo
| Mem of expression
and location = {x:int; y:int}
and varinfo = {vname:string; vorigname:string}
I can bind a variable of this type if the e_node
field is an integer:
let exp_const = {e_id=10;
e_node= Const 10;
e_loc={x=10; y=10}}
Now if I want that e_node
field to be of the Lval
type which is the record type lval
I can not figure out how to do it. I tried:
let exp_lval_var =
{e_id=11;
e_node= {vname="int_val"; vorigname="int_val1"};
e_loc={x=10; y=20}}
But it says that This expression has type varinfo but an expression was expected of type exp_node
. But if you follow the types, it is!?
Am I not defining types correctly here? Or am I not using the types correctly? I couldn't really find many more complex examples of using OCaml types. Any suggestions here would be appreciated.
Upvotes: 2
Views: 388
Reputation: 66803
Just like you wrote Const 10
(as opposed to just 10
), you need to write Lval (Var { ... })
to get the right kind of value for your e_node
field.
let exp_lval_var =
{e_id=11;
e_node= Lval (Var {vname="int_val"; vorigname="int_val1"});
e_loc={x=10; y=20}}
To follow the types for the first example:
10
is of type int
Const 10
is of type exp_node
For the second example
{vname="int_val"; vorigname="int_val1"}
is of type varinfo
Var {vname="int_val"; vorigname="int_val1"}
is of type lval
Lval (Var {vname="int_val"; vorigname="int_val1"})
is of type exp_node
Value constructors like Const
, Var
, and Lval
are not just labels for documentation in OCaml. They must appear as part of the expression to make a value of their type.
Upvotes: 1