Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing command-line arguments to an SML script

Tags:

sml

smlnj

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?

like image 230
abeln Avatar asked Oct 14 '13 15:10

abeln


People also ask

How do you pass command line arguments?

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.

How do you write a command line argument in shell script?

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.

How do you read a command line argument in Unix shell script?

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.


1 Answers

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.

like image 81
seanmcl Avatar answered Nov 05 '22 02:11

seanmcl