Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read command-line arguments in SML

Tags:

sml

I am trying to read the name of my input file that is argv[1] . This is what I’ve done so far :

val args = CommandLine.arguments() ;
val (x::y) =  args ;
val _ = agora x 

but I keep getting this error message :

uncaught exception Bind [nonexhaustive binding failure] .

Can anyone help ? Thank you in advance !

like image 813
Stelios Dr Avatar asked Nov 24 '25 06:11

Stelios Dr


1 Answers

This is the compiler warning you that you can't be sure that the bind pattern always holds.

For example, given the following program:

val args = CommandLine.arguments ()
val (x::y) = args
val _ = print (x ^ "\n")

Compiling and running this gives:

$ mosmlc args.sml
$ ./a.out Hello
Hello
$ ./a.out
Uncaught exception:
Bind

To safely handle a variable amount of command-line arguments, you might use a case-of:

fun main () =
    case CommandLine.arguments () of
         []     => print ("Too few arguments!\n")
       | [arg1] => print ("That's right! " ^ arg1 ^ "\n")
       | args   => print ("Too many arguments!\n")

val _ = main ()

Compiling and running this gives:

$ mosmlc args2.sml
$ ./a.out 
Too few arguments!
$ ./a.out hello
That's right! hello
$ ./a.out hello world
Too many arguments!

A side note: The equivalent of C's argv[0] is CommandLine.name ().

like image 133
sshine Avatar answered Nov 27 '25 14:11

sshine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!