Search code examples
typesocamlmutableref

How can I define a specific type for a mutable variable?


I'm a beginner in OCaml. I want to compile this code, but I get an error.

type pointeur_de_code = int;;
type environnement = int;;
type mlvalue =
 | Ml1 of int
 | Ml2 of pointeur_de_code * environnement;;
let (accu:mlvalue) = ref 0;;

This expression has type int ref but an expression was expected of type mlvalue


Solution

  • When you define a variant type like mlvalue you define constructors for values of the type. You have a constructor named Ml1 that takes an int and makes a value. And you have a constructor named Ml2 that takes two ints and makes a value.

    To make a value of the type, you need to include the constructor.

    In addition, the type of your accu can't be mlvalue. It must be mlvalue ref, which is a different type.

    let accu : mlvalue ref = ref (Ml1 0)
    

    (Note that you don't need to supply the type of accu. OCaml will infer the type for you.)