Search code examples
smlmosml

How to compile multiple SML files?


How does it work compiling multiple files in Standard-ML? I have 2 files.

file1.sml:

(* file1.sml *)
datatype fruit = Orange | Apple | None

And file2.sml:

(* file2.sml *)
datatype composite = Null | Some of fruit

So as you can see file2.sml is using stuff from file1.sml. How can I make this thing compile?

I am using mosmlc.exe and when compiling mosmlc file2.sml (as for this question):

(* file2.sml *)
use "file1.sml";
datatype composite = Null | Some of fruit

I get:

! use "file1.sml";
! ^^^
! Syntax error.

So, how to deal with multiple files?


Solution

  • You can read more in Moscow ML Owner’s Manual, but in your particular case the following command should work without even having to use use in the source code:

    mosmlc -toplevel file1.sml file2.sml
    

    Using Structure Mode

    When you want to organize your code into structure, you can use the -structure flag of mosmlc. For example, given the following files:

    Hello.sml

    structure Hello =
      struct
        val hello = "Hello"
      end
    

    World.sml

    structure World =
      struct
        structure H = Hello
    
        val world = H.hello ^ ", World!"
      end
    

    main.sml

    fun main () =
      print (World.world ^ "\n")
    
    val _ = main ()
    

    You can now obtain an executable called main, like this:

    mosmlc -structure Hello.sml World.sml -toplevel main.sml -o main
    

    And then run it:

    $ ./main
    Hello, World!
    

    Structure mode requires that you the name of the files and the contained structure coincide, just like in Java classes and files must have the same names. You can also use .sig files, which contain signatures.