问题
How do I go about passing command-line arguments to an SML script? I'm aware that there is a CommandLine.arguments()
function of the right type (unit -> string list
), but invoking the interpreter like so:
$ sml script_name.sml an_argument another_one
doesn't give me anything. Pointers?
回答1:
Try this.
(* arg.sml *)
val args = CommandLine.arguments()
fun sum l = foldr op+ 0 (map (valOf o Int.fromString) l)
val _ = print ("size: " ^ Int.toString (length args) ^ "\n")
val _ = print ("sum: " ^ Int.toString (sum args) ^ "\n")
val _ = OS.Process.exit(OS.Process.success)
The exit is important, otherwise you get a bunch of warnings treating the arguments as extensions. That is, it tries to parse the remaining arguments as files, but since they don't have an sml extension, they are treated as compiler extensions.
$ sml arg.sml 1 2 3
Standard ML of New Jersey v110.74 [built: Thu Jan 10 18:06:35 2013]
[opening arg.sml]
[autoloading]
[library $SMLNJ-BASIS/basis.cm is stable]
[autoloading done]
size: 3
sum: 6
val args = ["1","2","3"] : string list
val sum = fn : string list -> int
In programs compiled with MLton, commandline args are straightforward:
$ mlton arg.sml
$ ./arg a b c
size: 3
sum: 6
In SML/NJ it's more of a hassle to create a standalone executable.
来源:https://stackoverflow.com/questions/19363314/passing-command-line-arguments-to-an-sml-script