0

;; 关联列表 (al) 是

;; 空的或

;; (cons (list kv) alst), 其中

;; k 是一个 nat(密钥),

;; v 是一个字符串(值),并且

;; alst 是一个关联列表 (al)

updatestring 接受一个关联列表、一个数字 (findnum) 和一个字符串 (newstring),如果关联列表中有一个与 findnum 相同的数字,则它将列表中的字符串替换为 newstring。

(check-expect(updatestring empty 3 "hi") (list (list 3 "hi")))
(check-expect(updatestring (list (list 1 "hi")(list 5 "wow")) 5 "new")(list (list 1 "hi")(list 5 "new")))
(check-expect(updatestring (list (list 1 "hi")(list 5 "wow")) 2 "nice")(list (list 2 "nice") (list 1 "hi")(list 5 "wow")))

我遇到了代码问题,因为这就是我所拥有的。

(define (al-update alst akey avalue)
 (cond
  [(empty? alst) (list (list akey avalue))]
  [(= (first(first alst)) akey) (al-update (rest alst) akey avalue)]
  [else (list(list akey avalue alst))]))

问题是我的代码返回

(list (list 5 "new" (list (list 1 "hi") (list 5 "wow"))) instead of (list (list 1 "hi") (list 5 "new"))

(list(list 2 "nice" (list (list 1 "hi") (list 5 "wow")))) instead of (list (list 2 "nice") (list 1 "hi")(list 5 "wow")))

任何提示和答案将不胜感激,谢谢!

4

2 回答 2

1

您的递归结构需要是这样的:

(define (al-update alist akey avalue)
  (if (empty? alist)                                 ; base, end recusion
      '()
       (cons (let ((key+value (first alist)))        ; element, one-by-one
               (if (= ...)
                    ...
                    ...))
             (al-update (rest alist) akey avalue)))) ; recursion

在您的代码中存在许多问题。该else子句需要在列表的其余部分上递归。在=子句中,您需要进行替换和递归。在上面的代码中,我组合了两个递归子句。

于 2013-03-18T23:01:19.837 回答
0

它说“如果关联列表中有一个与 findnum 相同的数字,那么它将用 newstring 替换列表中的字符串”,但是在您的示例中,如果给定的数字不存在,则将其添加到列表中。

(check-expect (updatestring (list (list 1 "hi") (list 5 "wow")) 2 "nice")
              (list (list 2 "nice") (list 1 "hi") (list 5 "wow")))
(check-expect(updatestring empty 3 "hi") (list (list 3 "hi")))

代码和示例(测试)应该是这些:

(define (al-update alst akey avalue)
 (cond
  [(empty? alst) empty]
  [(= (first (first alst)) akey) (cons (list (first (first alst)) avalue)
                                       (al-update (rest alst) akey avalue))]
  [else (cons (first alst) (al-update (rest alst) akey avalue))]))


(check-expect (updatestring empty 3 "hi") empty)
(check-expect (updatestring (list (list 1 "hi") (list 5 "wow")) 5 "new")
              (list (list 1 "hi") (list 5 "new")))
(check-expect (updatestring (list (list 1 "hi") (list 5 "wow")) 2 "nice")
              (list (list 1 "hi") (list 5 "wow")))
(check-expect (updatestring (list (list 1 "hi") (list 5 "wow") (list 2 "bad")) 2 "nice")
              (list (list 1 "hi") (list 5 "wow") (list 2 "nice")))

顺便说一句,“car”相当于“first”,“cdr”相当于“rest”。

于 2013-05-14T19:20:53.833 回答