惯用的方式来编写Clojure代码从控制台重复读取行? [英] Idiomatic way to write Clojure code for repeatedly reading lines from the console?

查看:129
本文介绍了惯用的方式来编写Clojure代码从控制台重复读取行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我写了一个小的CLI脚本,需要从控制台重复读取日期(读取的日期的数量计算,可能每次都不同)。示例Ruby代码给你的想法:

Recently I was writing a little CLI script which needed to repeatedly read dates from the console (the number of dates to read was calculated and could be different each time). Sample Ruby code to give you the idea:

dates = x.times.collect { print "Enter date: "; Date.parse(gets.chomp) }

Clojure,并使用一些相当难看的代码 swap! loop ... recur 。我想知道什么最清洁的方式来实现期望的效果在Clojure将是。 (Clojure确实有 dotimes ,但它不保留从评估主体返回的值...从强调纯函数式编程的语言可以预期。)

Just for the heck of it, I wrote the script in Clojure, and wound up using some rather ugly code with swap! and loop...recur. I'm wondering what the cleanest way to achieve the desired effect in Clojure would be. (Clojure does have dotimes, but it doesn't retain the values returned from evaluating the body... as might be expected from a language which emphasizes pure functional programming.)

推荐答案

如果你的目标是结束一个正确的序列 x 用户输入的日期:

If your goal is to end up with a sequence of exactly x dates entered by user then:

(for [line (repeatedly x read-line)] (DateFormat/parse line))

或使用 map

(map DateFormat/parse (repeatedly x read-line))

注意Clojure中的延迟序列:用户将被要求输入更多的日期。如果您的目标是让用户一次输入所有日期(例如在启动时),请使用 doall

Beware of lazy sequences in Clojure: user will be asked to enter more dates as they are needed. If your goal is for user to enter all dates at once (say at startup) then use doall:

(map DateFormat/parse (doall (repeatedly x read-line)))

这会立即读取所有日期,但会懒惰地解析它们,因此日期格式验证可能会在您的程序中失败太久。您可以移动 doall 一级,以便及时解析:

This will read all dates at once, but will parse them lazily still, so date format validation could fail much later in your program. You can move doall one level up to parse promptly as well:

(doall (map DateFormat/parse (repeatedly x read-line)))

帮助函数以提示读取行:

And you can use a helper function to read line with prompt:

(defn read-line-with-prompt [prompt]
  (print prompt)
  (read-line))

-line :

Then replace read-line with either:

#(read-line-with-prompt "Enter date: ")

(partial read-line-with-prompt "Enter date: ")

这篇关于惯用的方式来编写Clojure代码从控制台重复读取行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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