17

I know that semicolons are used as terminators in REPL. But I'm confused about when to use them in a source file.

For example it is not necessary after val x = 1. But if I omit it after use "foo.sml", the compiler will complain about it.

Then, what are the rules on using semicolons?

dfeuer
  • 48,079
  • 5
  • 63
  • 167
Ben
  • 3,612
  • 3
  • 19
  • 24

1 Answers1

14

Semicolons are used for a number of syntactic entities in SML. They are normally used to create sequences of, e.g., expressions or declarations. Here's a link to the SML grammar:

http://www.mpi-sws.org/~rossberg/sml.html

In your case, you are interested in the semicolon for declarations (the dec class). Note that the semicolon that creates a sequence of decs is optional. You never actually need it when writing SML modules, and it is rare to see them. For example

structure S = struct
  val x = 5
  fun f x = x
  val z = x + x
end

not

structure S = struct
  val x = 5;
  fun f x = x;
  val z = x + x
end

In a source file, the only place you normally use a semicolon is separating expressions that have side-effects. For example,

val x = ref 5
val _ = (x := !x + 1; x := !x+ 2)

but this usage is rare.

The smlnj repl only evaluates declarations when it sees a semicolon though, so you should use a semicolon whenever you want to see or play with the value. I think the use "foo.sml"; case is confusing because it's not a declaration; it's an expression. I imagine that the repl converts expressions like use "foo.sml" into val _ = use "foo.sml". Thus it needs the semicolon to tell the repl to really run it, as above. As a side note, there is nothing special about use. It is simply a function of type string -> unit.

seanmcl
  • 9,740
  • 3
  • 39
  • 45
  • Thanks. Now I know why it isn't necessary in declarations. And then could you please explain why it is needed in `use "foo.sml";`? I still don't understant it. – Ben Oct 08 '13 at 03:45
  • Thanks for you clarification. Does it mean that in a source file (not REPL), if I write an expression in a single line, like `1+1`, I have to terminate it with an semicolon? – Ben Oct 08 '13 at 15:08
  • Yes, unless you want the expression to continue to the next line, e.g. `1\n +\n 1;` As a rule of thumb, use semicolon in the repl when you want to see the result. – seanmcl Oct 08 '13 at 15:09