Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get user input in Clojure?

I'm currently learning clojure, but I was wondering how to get and store user input in a clojure program. I was looking at the clojure api and I found a function called read-line, however I'm not sure how to use it if it's the right function to use...

Anyhow, how do you get user input in clojure ?

like image 848
JoOb Avatar asked Jul 11 '09 21:07

JoOb


People also ask

How do I get input in Clojure?

Getting user input in clojure In clojure, you can get user input with the read-line function. The conversion to an integer is also necessary and you can use Integer/parseInt for that. read-line doesn't have prompt feature, so we will print the prompt to the console with println .


3 Answers

read-line is the correct function..

(println (read-line))

..would basically echo the users input:

Clojure 1.0.0-
user=> (println (read-line))
this is my input
this is my input

To use it in an if statement, you'd probably use let:

(let [yayinput (read-line)]
  (if (= yayinput "1234")
    (println "Correct")
    (println "Wrong")))

Hope that's enough to get you started, because that's about the limit of my Clojure knowledge!

like image 200
dbr Avatar answered Nov 02 '22 11:11

dbr


Remember also that you have access to all of Java ...

OK so perhaps I should present some examples ... my clojure skills are not good so these examples may need a bit of tweaking.

The System.console() way:

(let [console (. System console)
     pwd (.readPassword console "tell me your password: ")]
   (println "your password is " pwd))

The BufferedReader way:

(print "give me a line: ")
(let [reader (java.io.BufferedReader. *in*)
     ln (.readLine reader)]
   (println "your line is " ln))

My point is that one can leverage knowledge of Java, and Java itself, in Clojure. It's one of its principal, advertised strengths.

Wonder what would my score have been if the question were about user input from a GUI!

By the way, you could use JOptionPane to put up a little GUI to get user input ...

like image 32
Allen Avatar answered Nov 02 '22 09:11

Allen


read-line is used to get user input and use let to bind it to some variable.

For example : if you want to read user ID and password from user and display it, you could use the following piece of code

(defn print-message [pid pw] 
(println "PID : " pid)
 (println "PW : " pw))

(defn inp[]
(println "Enter your PID and password") 
(let[pid (read-line) pw (read-line)] 
(print-message pid pw) ))
like image 2
Vj l Avatar answered Nov 02 '22 11:11

Vj l