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) }
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.)
read-line returns nil when the end of file is reached. On the console that is when you press CTRL-d (CTRL-z on Windows).
You could use this code to take advantage of this:
If you must read a fixed number of lines you can use:
If your goal is to end up with a sequence of exactly
x
dates entered by user then:or using
map
: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
: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:And you can use a helper function to read line with prompt:
Then replace
read-line
with either:or
You can do something like this: