Stelios Dr
Stelios Dr

Reputation: 115

Read command-line arguments in 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 !

Upvotes: 3

Views: 456

Answers (1)

sshine
sshine

Reputation: 16105

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 ().

Upvotes: 3

Related Questions