Ocaml 中的运算符

Functor in Ocaml

我对 Ocaml 中的函子有疑问。我有这种情况:

module type EveryType = 
    sig
        type t
        val str : t -> string
    end;;
module type StackInterface =
    functor (El : EveryType) ->
    sig
        type el = El.t
        type stack
        exception EmptyStackException
        val empty : stack
        val pop : stack -> stack 
        val top : stack -> el
        val push : stack -> el -> stack
        val str : stack -> string
    end;; 
module StackImpl (El : EveryType) =
    struct
        type el = El.t
        type stack = Empty | Node of el * stack
        exception EmptyStackException

        let empty = Empty

        let pop s =
            match s with
                | Empty -> raise EmptyStackException
                | Node(_, t) -> t

        let top s =
            match s with
                | Empty -> raise EmptyStackException
                | Node(h, _) -> h

        let push s el = Node(el, s) 

        let str s = 
            let rec str s =  
                match s with                    
                    | Node(h, Empty) -> El.str h ^ ")"
                    | Node(h, t) -> El.str h ^ ", " ^ str t
                    | _ -> ""
            in 
            if s == Empty then
                "Stack()"
            else
                "Stack(" ^ str s
    end;;

module Stack = (StackImpl : StackInterface);;
module TypeChar =
    struct
        type t = char
        let str c = Printf.sprintf "%c" c
    end;;
module StackChar = Stack(TypeChar);;
module CheckExp(St : module type of StackChar) =
struct
    let checkExp str =            
        let rec checkExp str stk = 
            try 
                match str with
                    | [] -> true
                    | '(' :: t -> checkExp t (St.push stk '(')  
                    | ')' :: t  -> checkExp t (St.pop stk)
                    | _ :: t ->  checkExp t stk
            with St.EmptyStackException -> false
        in checkExp (explode str) St.empty
end;;

我用仿函数创建了一个 Stack 来拥有各种类型的堆栈。现在我想在将 parantesis 检查到表达式中的函数中使用此堆栈(类型为 char)。但是编译器给我这个错误: Unbound module type StackChar refered to line module CheckExp(St : StackChar) =

我做错了什么???

StackChar 是一个模块,但是函子需要的是一个模块 type。如果您总是将同一个模块传递给它,那么它就不是一个函子。最简单的解决方法是将其替换为 module type of StackChar:

module CheckExp(St : module type of StackChar) =
    struct
        ...
    end

但是你确定你真的需要一个仿函数吗?