Passing command-line arguments to an SML script

*爱你&永不变心* 提交于 2019-12-07 02:51:55

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!