Функтор в Окамле - PullRequest
       12

Функтор в Окамле

0 голосов
/ 16 октября 2019

У меня проблема с функтором в Окамле. У меня есть такая ситуация:

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

Я создаю стек с функтором, чтобы иметь стек каждого типа. Теперь я хочу использовать этот стек (с типом char) в функции, которая проверяет парантез в выражении. Но компилятор выдает мне эту ошибку: Несвязанный тип модуля StackChar ссылается на строку Модуль CheckExp (St: StackChar) =

В чем я ошибся ???

1 Ответ

1 голос
/ 16 октября 2019

StackChar - это модуль, но для функтора нужен модуль тип . Это не будет большим функтором, если вы всегда передадите ему один и тот же модуль. Самое простое решение для этого - заменить его на module type of StackChar:

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

Но вы уверены, что вам действительно нужен функтор здесь?

...