【问题标题】:How can I define a specific type for a mutable variable?如何为可变变量定义特定类型?
【发布时间】:2019-03-12 06:13:48
【问题描述】:

我是 OCaml 的初学者。我想编译这段代码,但我得到一个错误。

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

此表达式的类型为 int ref,但表达式应为 mlvalue 类型

【问题讨论】:

    标签: types ocaml mutable ref


    【解决方案1】:

    当您定义像mlvalue 这样的变体类型时,您可以为该类型的值定义构造函数。您有一个名为 Ml1 的构造函数,它接受 int 并生成一个值。你有一个名为 Ml2 的构造函数,它接受两个 ints 并生成一个值。

    要生成类型的值,您需要包含构造函数。

    另外,你的accu的类型不能是mlvalue。必须是mlvalue ref,这是一个不同的类型。

    let accu : mlvalue ref = ref (Ml1 0)
    

    (请注意,您不需要提供accu 的类型。OCaml 会为您推断类型。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-15
      • 2018-04-20
      • 1970-01-01
      • 1970-01-01
      • 2014-07-30
      • 1970-01-01
      相关资源
      最近更新 更多