Functor实现问题

时间:2010-10-28 10:29:54

标签: ocaml functor

下面描述的模块的目的是实现一个模块,该模块一旦由整数n启动,就基于n的值执行所有操作。

module ReturnSetZero =
functor ( Elt : int ) ->
    struct
        let rec sublist b e l =
               match l with
           [] -> failwith "sublist"
          | h :: t ->
              let tail = if e = 0 then [] else sublist (b - 1) (e - 1) t in
                    if b > 0 then tail else h :: tail
        let rec zerol = 0:: zerol
        let zeron = sublist 0 n zerol
                (*other operations based on n which is selected once when the module is initialized*)
    end;;

错误:未绑定模块类型int

这是什么问题?是否有更有效/直观的替代实施?

1 个答案:

答案 0 :(得分:2)

仿函数将模块映射到模块。整数不是模块,因此您不能将其用作函子参数。

您需要定义模块类型:

module type WITH_INTEGER = sig
  val integer : int
end

module PrintInteger = 
  functor (Int:WITH_INTEGER) -> struct

  let print_my_integer () = print_int Int.integer

当然,除非你的模块需要暴露依赖于整数值的类型(或者你必须暴露很多依赖于整数的值),你可能最好使用一个简单的函数来完成该整数作为参数:

let my_function integer = 
  let data = complex_precomputations integer in 
  function arg -> do_something_with arg data

这使您可以在整数上运行复杂的预计算(当您将其传递给函数时)。