Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure's (read-line) returns nil; does not prompt

Tags:

clojure

I'm working on my first proper Clojure program--a chess game. I have the following:

(defn human-move [board]
  (board-utils/print-board board)
  (print "Enter your move, like this: 'E7 E5' ...")
  (loop [raw-move (terminal-input)] ;;(read-line)]
    (println "I just received" raw-move)
    (if (re-matches #"[A-H][1-8]\s[A-H][1-8]" raw-move)
      (parse-move raw-move)
      (do
        (println "Invalid format! There should be a letter, number, space, letter, and final number.")
        (print "Try again: ")
        (recur (read-line))))))

Note the place where read-line is commented out and replaced by terminal-input. read-line was giving me a NullPointerException, so for diagnostic purposes:

(defn terminal-input []
  (println "input")
  (let [whatnot (read-line)]
    (println "received" whatnot)
    whatnot))

Then, when I call human-move.

...
+---+---+---+---+---+---+---+---+
| P | P | P | P | P | P | P | P |
+---+---+---+---+---+---+---+---+
| R | N | B | Q | K | B | N | R |
+---+---+---+---+---+---+---+---+
Enter your move, like this: 'E7 E5' ...input
received nil
I just received nil

I never got a chance to type something in as input. Were this Java, I'd start playing little games with the garbage collector (calling Scanner.next(), for instance), but with Clojure I didn't know what to do besides putting the (flush) in there.

For what it's worth, this is with SLIME.


I also tried to have terminal-input provide dummy data, and learned that I'm apparently using loop/recur incorrectly. I haven't investigated it super-thoroughly though, since I've been distracted by the read-line issues.

Thanks in advance.

like image 480
tsm Avatar asked May 02 '11 19:05

tsm


2 Answers

This will work now with swank-clojure 1.4.0-SNAPSHOT if you wrap the call to read-line in swank.core/with-read-line-support like this

(with-read-line-support (println "a line from Emacs:" (read-line))

https://github.com/technomancy/swank-clojure/commit/f4a1eebc4d34f2ff473c4e5350f889ec356f5168

like image 69
Tavis Rudd Avatar answered Nov 07 '22 01:11

Tavis Rudd


read-line doesn't work in SLIME. I can't find the discussion thread about this, but it's true.

like image 27
amalloy Avatar answered Nov 06 '22 23:11

amalloy