函数体的函数体,该函数使用大学的复合数据列表并生成学费最低的学校名称。BSL球拍

Function body for a function that consumes a compound data list of universities and produces the name of school with the lowest tuition. BSL RACKET

提问人:BTDN 提问时间:2/18/2023 最后编辑:BTDN 更新时间:2/18/2023 访问量:59

问:

大家好,我在为函数编码正文时遇到了问题 使用大学的复合数据列表,并生成学费最低的大学名称。

语言是BSL Racket。

复合数据定义:

(define-struct uni (name tuition))

interp. a university name as a string and its tuition as a 
natural

(define UNI-1 (make-uni "UBC" 28500))
; example of compound data definition

大学的列表数据定义:

ListOfUni is one of:
  - empty
  - (cons uni ListOfUni)
 interp. a list of unis

(cons (make-uni "SFU" 27797) (cons (make-uni "UVIC" 26000) 
    empty))

功能介绍:

 (lowest? lou) 

This is a function that consumes list of unis and produces the 
name of school with the lowest tuition 

检查预期:

(check-expect (lowest? empty) "none")
(check-expect (lowest? (cons (make-uni "UBC" 28500) empty)) 
"UBC")
(check-expect (lowest? (cons (make-uni "SFU" 27797) (cons (make- 
uni "UVIC" 26000) empty))) "UVIC")

函数体的尝试:

 (define (lowest? lou)
  (cond [(empty? lou) "none"]
        [(empty? (rest lou)) (uni-name (first lou))]
        [else (if  (<(uni-tuition (first lou)) (uni-tuition (lowest? (rest lou))))
                (uni-name (first lou))
                (lowest? (rest lou)))]))

给出的错误消息:

1 of the 3 tests failed.

Check failures:
 check-expect encountered the following error instead of the 
expected value, "UVIC". 
   :: uni-tuition: expects an uni, given "UVIC"

我不明白如何解决这个错误,并且仍然让代码是递归的。

另外,请原谅任何格式错误,这是我在 StackOverFlow 上的第一篇文章

函数 递归 语法-错误 球拍 自引用

评论


答:

0赞 Martin Půda 2/18/2023 #1

当你遍历大学列表时,你必须从每个步骤返回结构,因为你调用了结果:uniuni-tuition(uni-tuition (lowest? (rest lou)))

但是当只有一个元素时,你的函数会返回一个字符串。这就是错误消息的含义: :: uni-tuition: expect an uni, given “UVIC”lou(uni-name (first lou))

可能还有更多方法可以解决这个练习,但考虑到 BSL 的限制(no 和 work only for 和 values),我不得不想出 helper 函数和“none”大学创建:letorand#true#false(make-uni "none" 0)

(define-struct uni (name tuition))

(define (lowest-helper lou)
  (cond [(empty? lou) (make-uni "none" 0)]
        [(empty? (rest lou)) (first lou)]
        [(< (uni-tuition (first lou))
            (uni-tuition (lowest-helper (rest lou))))
         (first lou)]
        [else
         (lowest-helper (rest lou))]))

(define (lowest? lou)
  (uni-name (lowest-helper lou)))

(check-expect (lowest? empty) "none")
(check-expect (lowest? (cons (make-uni "UBC" 28500) empty)) 
"UBC")
(check-expect (lowest? (cons (make-uni "SFU" 27797)
                             (cons (make-uni "UVIC" 26000) empty))) "UVIC")

或者,您可以返回 either 或 struct 并添加一个新函数来区分它们:"none"uni

(define (get-name result)
  (if (string? result)
      result
      (uni-name result)))

(define (lowest? lou)
  (get-name (lowest-helper lou)))