【问题标题】:Condition using char in Scheme在 Scheme 中使用 char 条件
【发布时间】:2021-08-19 10:54:03
【问题描述】:

我试图在 if-else 语句中使用 char 作为条件,但条件似乎只能接受整数输入。

这是我的代码:

(display "Presenter - R \nParticipant - P")

(define (option)
  (define r(read))
(cond
  ((= r R )
   (display "Presenter: \nLocal - RM1272\nInternational - RM1474"))
  ((= r P )
   (display "Participant: \nLocal - RM795\nInternational - RM800"))
))

输出:

Presenter - R 
Participant - P
> (option)
R
. . =: contract violation
  expected: number?
  given: r 

【问题讨论】:

  • = 仅适用于数字。您需要找到适用于更一般类型的谓词。
  • 就用equal?
  • 使用equal? 不起作用。

标签: if-statement char scheme racket


【解决方案1】:

(read) 的结果是符号 R,它既不是字符也不是标识符。
您也可以只使用= 来比较数字。

> (define r (read))
R
> r
'R
> (equal? r R)
. . R: undefined;
 cannot reference an identifier before its definition
> (equal? r #\R)
#f
> (equal? r 'R)
#t

【讨论】:

  • 然后它应该在 if-else 语句中显示演示者或参与者的价格。您的编码确实会在输出端显示任何价格。
  • 这只是说明您的假设有什么问题以及您应该做什么。您需要应用这些知识并自己完成代码。
  • 而且条件是表达式,不是语句。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-15
  • 2015-12-14
  • 2010-09-11
  • 2013-10-09
  • 2011-03-13
  • 1970-01-01
相关资源
最近更新 更多