3

下面描述的模块的目的是实现一个模块,该模块一旦由整数 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

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

4

1 回答 1

2

A functor maps modules to modules. An integer is not a module, so you cannot use it to as a functor parameter.

You need to define a module type:

module type WITH_INTEGER = sig
  val integer : int
end

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

  let print_my_integer () = print_int Int.integer

end

Of course, unless your module needs to expose types that are dependent on the value of the integer (or you have to expose a lot of values dependent on that integer), you're probably better off with a plain function that takes that integer as an argument:

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

This lets you run the complex pre-computations only once on the integer (when you pass it to the function).

于 2010-10-28T10:54:33.903 回答