Ocaml中的函子
我对Ocaml中的函子有问题。我有这样的情况:Ocaml中的函子,ocaml,functor,Ocaml,Functor,我对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 Emp
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;;
我使用functor创建了一个堆栈,以拥有每种类型的堆栈。现在,我想在一个函数中使用这个类型为char的堆栈,将parantesis检查到一个表达式中。但编译器给了我这个错误:未绑定的模块类型StackChar引用了行模块CheckExpSt:StackChar=
我错了什么?StackChar是一个模块,但函子需要的是一个模块类型。如果总是传递同一个模块,它就不会是一个函子。最简单的修复方法是将其替换为模块类型StackChar:
模块CheckExpSt:StackChar的模块类型=
结构
...
终止
但是你确定你真的需要一个函子吗