一个简单的 Racket 终端交互 [英] A simple Racket terminal interaction

查看:36
本文介绍了一个简单的 Racket 终端交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习 Racket-lang,我想编写一个简单的程序,从终端读取数据,对输入进行处理并做出响应.

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.

这是用 Python 编写的程序:

Here's that program in Python :

while True :
    l = raw_input()
    print somefunction(l)

我应该如何在 Racket 中编写等效的代码?

How should I write the equivalent in Racket?

推荐答案

该程序在球拍中的等价物是这样的:

The equivalent of that program in racket would be this:

(for ([line (in-lines)])
  (displayln (some-function line)))

如果您只想将结果打印到标准输出.如果您想将结果用作传递给其他表达式的值,for/list 返回这些值的列表:

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

这更有用,因为该列表可以被程序的其他部分使用.但是,它在获取整个列表之前不会为您提供列表,这仅在到达 eof 时发生(如果用户键入 ctrl-D 或等效项).实际上,您可能需要一个特定条件让用户说我已经完成了,这就是我要输入的全部内容,至少现在是这样."为此,您可以使用带有 #:break stop-condition 子句的相同形式:

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/fold,或者您可以使用递归函数调用自身来请求更多输入.递归函数往往更灵活.

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.

这篇关于一个简单的 Racket 终端交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆