OCaml - 将参数化函数添加到模块时出错

时间:2015-04-01 00:14:30

标签: functional-programming ocaml

我想扩展这个给定的定义:

module type StateChart = sig
    type 'a t
    val get : 'a t -> 'a
    val create : 'a -> 'a t
end


module ConcreteStateChart : StateChart = struct
    type 'a t = { state : 'a } (* internal configuration and current state expressed as 'a parameter *)
    let get m = m.state;;   (* obtaining the internal value *) 
    let create x = { state = x };;
end

分为两个模块,可以执行k类型的任何类型的事务。我尝试定义以下代码,但是:

module type StateChart = sig
    type 'a t
    type k
    val get : 'a t -> 'a
    val create : 'a -> 'a t
    val transaction : 'a t -> k -> 'a t
end


module ConcreteStateChart : StateChart = struct
    type 'a t = { state : 'a } (* internal configuration and current state expressed as 'a parameter *)
    type k = 'a option
    let get m = m.state;;   (* obtaining the internal value *) 
    let create x = { state = x };;
    let transaction x y = (* Stupid StateChart that changes the state dependingly to an option parameter *)
        match y with
        | Some z -> { state = z}
        | None -> x;;   
end

似乎k定义并不记得在' a 中执行的' a 绑定:

  

键入k = ' a 选项;;

     

错误:未绑定的类型参数' a

我如何定义这样的事务,以后可以在 ConcreteStateChart 模块中实现?

1 个答案:

答案 0 :(得分:1)

必须量化数据类型定义右侧出现的类型变量:k应定义为类型参数:

type 'a k = 'a option

您要表达的内容,k必须是t内容类型的选项,不能在数据类型定义的级别中表达,而是在{{1}中使用它们}}:

transaction

,表示val transaction : 'a t -> 'a k -> 'a t t的内容类型必须相同。

相关问题