mercury

Building Multi-Module Mercury Programs


Q. What's a simple template for building a two-module mercury program? Module_1 defines and exports a simple function or predicate. Module_2 imports the function/predicate to compute a useful result and outputs the result.


Solution

  • I would use the following approach, first define the module with the function(s) or predicate(s) or predicates you want to export (interface section):

    % File: gcd.m
    
    :- module gcd.
    
    :- interface.
    :- import_module integer.
    
    :- func gcd(integer, integer) = integer.
    
    :- implementation.
    
    :- pragma memo(gcd/2).
    gcd(A, B) = (if B = integer(0) then A else gcd(B, A mod B)).
    

    The file using the exported function in the gcd module (gcd/2):

    % File: test_gcd.m
    
    :- module test_gcd.
    
    :- interface.
    
    :- import_module io.
    
    :- pred main(io::di, io::uo) is det.
    
    :- implementation.
    
    :- import_module char.
    :- import_module gcd.
    :- import_module integer.
    :- import_module list.
    :- import_module std_util.
    :- import_module string.
    
    main(!IO) :-
        command_line_arguments(Args, !IO),
        ArgToInteger = integer.det_from_string `compose` list.det_index0(Args),
    
        A = ArgToInteger(0),
        B = ArgToInteger(1),
    
        Fmt = (func(Integer) = s(integer.to_string(Integer))),
        GCD = gcd(A, B),
        io.format("gcd(%s, %s) = %s\n", list.map(Fmt, [A, B, GCD]), !IO).
    

    To compile and run on Windows (cmd.exe): Please note that mmc is also a Windows system command, so please use the Mercury environment provided by the Mercury distribution installer:

    > mmc --use-grade-subdirs -m test_gcd
    > test_gcd 12 4
    

    To compile and run on Linux/MacOS/etc (any Bash-like shell):

    $ mmc --use-grade-subdirs -m test_gcd
    $ ./test_gcd 12 4