问题
I am new to the SML language and I want to do this:
- to ask a person "what is your full name?"
- to get answer from user's keyboard
- and to write "your full name is"+name (his or her name that answered)
回答1:
This answer has three parts. The first part answers your only question. The second part answers a question you seem to be fishing for without asking it, and the third part addresses how to find answers to questions by your own means.
How to read string from user keyboard in SML language?
You use TextIO.inputLine TextIO.stdIn
:
- val wat = TextIO.inputLine TextIO.stdIn;
Hello, World!
val wat = SOME "Hello, World!\n" : string option
Notice that this actually doesn't work in my Poly/ML REPL (aka "the top-level" or "the prompt"), but it does work in both of my SML/NJ and Moscow ML REPLs, but it will probably work from within an .sml file that you compile or run.
Notice also that you'll get the linebreak as well. Maybe you don't want that.
Although you didn't ask, you can print a string in much the same way:
- TextIO.output (TextIO.stdOut, Option.valOf wat);
Hello, World!
val it = () : unit
The catch here is that when you read a line from the user, you might not get anything, which results in the value NONE
rather than an empty string (what you'd expect in Python) or an exception (what you'd expect in Java). And when you get something, to be able differentiate between getting an empty response and not getting a response, you get SOME "..."
.
If you don't care about this distinction, you can also make life easier and build some helper functions:
(* helper functions *)
fun getLine () =
Option.getOpt (TextIO.inputLine TextIO.stdIn, "")
fun putLine s =
TextIO.output (TextIO.stdOut, s)
(* examples of use *)
val wat = getLine ()
val _ = putLine (wat ^ "!!!")
When you get around to want to ask similar questions, you can find some of these answers yourself by typing open TextIO;
Enter in your REPL. This tells you what functions are available inside the TextIO module, but not necessarily what they do. So what you can do is also look up the documentation by googling around:
https://smlfamily.github.io/Basis/text-io.html
来源:https://stackoverflow.com/questions/62236458/how-to-read-string-from-user-keyboard-in-sml-language