Marco Mantovani
Marco Mantovani

Reputation: 121

Functor in Ocaml

I have a problem with functor in Ocaml. I have this situation:

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;;

I create a Stack with functor to have a stack of every type. Now I want to use this stack (with type char) in a function that check parantesis into an expression. But compiler gives me this error: Unbound module type StackChar refered to line module CheckExp(St : StackChar) =

What have I wrong???

Upvotes: 0

Views: 116

Answers (1)

glennsl
glennsl

Reputation: 29106

StackChar is a module, but what you need for a functor is a module type. It wouldn't be much of a functor if you always pass it the same module. The simplest fix for this is to replace it with module type of StackChar:

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

But are you sure you actually need a functor here?

Upvotes: 1

Related Questions