首页 > 解决方案 > 如何在 GNU Guile 中读取字符串以获取用户输入?

问题描述

我正在尝试制作一个石头剪刀布游戏来帮助自己学习 GNU Guile。我遇到了用户输入的障碍,即玩家在游戏中的选择。如果我将其设置为字符串,则游戏可以正常运行。如果我使用(read),我会从查找中返回 #f 作为类型。我尝试格式化读取以尝试使其成为字符串,但没有成功。

(define (print a)
  (display a)
  (newline))

(define choices (make-hash-table 3))
(hashq-set! choices "r" "s")
(hashq-set! choices "s" "p")
(hashq-set! choices "p" "r")

(define (cpu-choice) (list-ref (list "r" "p" "s") (random 3)))

(print "You are playing rock paper scissors.")
(print "Type r for rock, p for paper, and s for scissors.")
(define draw
  ;; "s" ; This works as a test.
 (read (open-input-string (read))) ; Can't get user in as string, so the hashq-ref will work.
  )

(define cpu-draw (cpu-choice))

;; debug
(print (format #f "Player enterd ~a" draw))
(print (format #f "Player needs to with ~a" (hashq-ref choices draw))) ; Keeps coming back as #f
(print (format #f "CPU has entered ~a" cpu-draw))

;; norm
(newline)
(when (eq? draw cpu-draw)
  (print "There was a tie")
  (exit))

(when (eq? (hashq-ref choices draw) cpu-draw)
  (print "You have won.")
  (exit))

(print "You have failed. The computer won.")

如何从用户那里获取字符串?可能类似于(str (read))(read-string)(读作字符串)。

$ guile --version
guile (GNU Guile) 2.0.13

更新

我只想提一下,虽然批准的答案是正确的,但我不明白 Guile/Scheme 在写这篇文章时是如何处理字符串和符号的。我让程序工作的唯一方法是choicescpu-choice列表中的所有字符串更改为符号。前任:

(hashq-set! choices 'r 's)
(list 'r 'p 's)

感谢奥斯卡洛佩斯的帮助。

标签: schemecommand-line-interfacelispuser-inputguile

解决方案


除非您用双引号将输入括起来,否则您键入的值将被解释为符号。试试这个:

(define str (read))
> "hello"

或这个:

(define str (symbol->string (read)))
> hello

无论哪种方式,str现在都将保存一个实际的字符串:

str
=> "hello"

推荐阅读