Search code examples
ozmozart

Mozart error "illegal use of nesting marker" when creating a functor


When compiling an Oz code with a functor, I get the error "illegal use of nesting marker" on the line where "functor" is declared. What can this mean?

functor
export
    sum:Sum
    divisao:Div
    mult:Mult
    sub:Sub
define
    fun {Sum X Y} X + Y end
    fun {Mult X Y} X * Y end
    fun {Sub X Y} X - Y end
end

Solution

  • First, you are missing the definition of Div.

    functor
    export
       sum:Sum
       divisao:Div
       mult:Mult
       sub:Sub
    define
       fun {Sum X Y} X + Y end
       fun {Mult X Y} X * Y end
       fun {Sub X Y} X - Y end
       fun {Div X Y} X / Y end
    end
    

    functors are meant to be the definition of modules where your define imports and exports, as files. You should compile the file and turn it into a module. For example, call your file test.oz and run the following commands to compile and run.

    ozc -c test.oz && ozengine test.ozf
    

    If you are running Mozart by feeding a buffer to the compiler, you cannot directly use functor as you have to turn it into a module. You have to declare it first, and apply it using the Module.manager.

    declare F M ModMan
    F = functor
        export
            sum:Sum
            divisao:Div
            mult:Mult
            sub:Sub
        define
            fun {Sum X Y} X + Y end
            fun {Mult X Y} X * Y end
            fun {Sub X Y} X - Y end
            fun {Div X Y} X / Y end
        end
    
    % To use the functions of the functor, apply it and create a module
    ModMan = {New Module.manager init}
    M = {ModMan apply(F $)}
    
    % Then use the exported functions with module M
    % Example:
    {Show {M.sum 3 5}}
    % >>> 8