1
(define-struct student (first last major age))

(define student1 (make-student "David" "Smith" 'Math 19))
(define student2 (make-student"Joe" "Jones" 'Math 21))
(define student3 (make-student "Eli" "Black" 'Spanish 20))

(define (same-age? s1 s2)
  (string=? (student-age s1)
            (student-age s2)))

因此,如果两个学生年龄相同,我试图将布尔值作为输出,但是当我运行它时,它说它需要一个字符串作为第一个参数,但给出了 19。问题是什么?

4

2 回答 2

3

您的几个问题是相关的,您似乎在比较不同的数据类型时遇到困难,这里有一些提示:

  • 比较数字时,使用=
  • 比较字符时,使用char=?
  • 比较符号时,使用symbol=?
  • 比较字符串时,使用string=?
  • 或者简单地使用equal?, 适用于多种类型的包罗万象的过程,只要其两个操作数的类型相同且相等,它就会返回 true

例如,以下所有比较都将返回#t

(equal? 1 1)
(equal? 1.5 1.5)
(equal? #\a #\a)
(equal? 'x 'x)
(equal? "a" "a")
(equal? (list 1 2 3) (list 1 2 3))
于 2013-01-28T00:47:22.503 回答
1

您创建学生的age字段是整数,而不是字符串(注意缺少双引号),然后尝试使用string=?函数来比较它们。您应该使用该=函数进行比较age

(define-struct student (first last major age))

(define student1 (make-student "David" "Smith" 'Math 19))
(define student2 (make-student "Joe" "Jones" 'Math 21))
(define student3 (make-student "Eli" "Black" 'Spanish 20))

(define (same-age? s1 s2)
  (= (student-age s1)
     (student-age s2)))

或创建学生,他们的age字段表示为字符串:

(define-struct student (first last major age))

(define student1 (make-student "David" "Smith" 'Math "19"))
(define student2 (make-student "Joe" "Jones" 'Math "21"))
(define student3 (make-student "Eli" "Black" 'Spanish "20"))

(define (same-age? s1 s2)
  (string=? (student-age s1)
            (student-age s2)))
于 2013-01-28T00:08:12.970 回答