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?
To pass command line arguments, we typically define main() with two arguments : first argument is the number of command line arguments and second is list of command-line arguments. The value of argc should be non negative. argv(ARGument Vector) is array of character pointers listing all the arguments.
Pass arguments from command line - shell script To pass arguments from the command line, add the argument values after the file name while executing the script. In script $1 will refer the value of agr1, and $2 will refer the value of arg2 and so on.
The special character $# stores the total number of arguments. We also have $@ and $* as wildcard characters which are used to denote all the arguments. We use $$ to find the process ID of the current shell script, while $? can be used to print the exit code for our script.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With