

Task

Obtain a valid   Y   or   N   response from the keyboard.

The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated.

The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need to press an   enter   key.




 
#lang racket
 
;; GUI version
(require racket/gui)
(message-box "Yes/No example" "Yes or no?" #f '(yes-no))
 
;; Text version, via stty
(define stty
  (let ([exe (find-executable-path "stty")])
    (λ args (void (apply system* exe args)))))
(define tty-settings (string-trim (with-output-to-string (λ() (stty "-g")))))
(printf "Yes or no? ") (flush-output)
(stty "-icanon" "-echo" "min" "1")
(let loop () (when (char-ready?) (loop)))
(let loop ()
  (define ch (read-char))
  (case (char-downcase ch)
    [(#\y #\Y #\n #\N) (displayln ch) (if (memq ch '(#\y #\Y)) 'yes 'no)]
    [else (loop)]))
(stty tty-settings)
 