问题
I'm just starting learning Racket-lang, and I want to write a simple program that reads from the terminal, does something with the input and responds.
Here's that program in Python :
while True :
l = raw_input()
print somefunction(l)
How should I write the equivalent in Racket?
回答1:
The equivalent of that program in racket would be this:
(for ([line (in-lines)])
(displayln (some-function line)))
That's if you want to just print the results to stdout. If you want to use the results as a value to pass to some other expression, for/list returns a list of those values:
(for/list ([line (in-lines)])
(some-function line))
Which is much more useful, because that list can be used by other parts of the program. However, it doesn't give you the list until it can get the entire list, which only happens when it gets to eof (if the user types ctrl-D or the equivalent). In reality you might want a specific condition for the user to say "I'm done, this is all I'm going to type, at least for now." For that, you would use the same form with a #:break stop-condition clause:
(for/list ([line (in-lines)]
#:break (string=? line "done"))
(some-function line))
For more complicated interactions with the user, you might want to keep track of some state that changes as the user enters more stuff. In that case, you can use for/fold, or you can use a recursive function that calls itself to ask for more input. A recursive function tends to be more flexible.
来源:https://stackoverflow.com/questions/35192335/a-simple-racket-terminal-interaction