0

say I want to have user input a matrix row by row. So I first ask for the size of the matrix, then I would like to ask for user input rows with prompt like "row 1" "row 2" etc.

The most trivial thing to do seems like to have a mutable vector and use somethinkg like doseq to mutate it.

But I'm curious if there are any more clojure way to do it. My initial thought was to use for or map. But it is lazy so cannot print out the prompt.
so something like (map (fn [i] (do (printf "row %d \n" i) (read-line))) (range size)) will include prompt in the result list as well.

Then I thought I could use a macro to just produce something like

[((println "row i") (read-line)) 
 ((println "row i") (read-line)) 
 ((println "row i") (read-line)) ...]

Are there anyway I can do this without macro or mutable variable? Which way is better?

LoveProgramming
  • 2,121
  • 3
  • 18
  • 25

2 Answers2

0

Take a look at this question for information around idiomatic ways to read multiple lines from the console.

Community
  • 1
  • 1
Jared314
  • 5,181
  • 24
  • 30
0

The following does what you ask for, provided I understand your question properly:

(loop [i   (read-line)
       ret []]
  (println "row" i)
  (if (some-condition)
    ret
    (recur (read-line) (conj ret i))))

For example, having the condition as (= i "x"):

user=> (loop [i (read-line) ret []] (println "row" i) (if (= i "x") ret (recur (read-line) (conj ret i))))
SOME
row SOME
some
row some
XXXX
row XXXX
my my my
row my my my
1
row 1
2
row 2
3
row 3
4
row 4
5
row 5
x
row x
["SOME" "some" "XXXX" "my my my" "1" "2" "3" "4" "5"]
user=> 
dsm
  • 10,263
  • 1
  • 38
  • 72