;;关联列表(al)是
;;空或
;; (cons(list k v)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")))
非常感谢任何提示和解答,谢谢!
答案 0 :(得分: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
子句需要递归列表的其余部分。在=
子句中,您需要进行替换和递归。在上面的代码中,我结合了两个递归的条款。
答案 1 :(得分:0)
它说“如果在关联列表中有一个与findnum相同的数字,那么它会用新闻字符串替换列表中的字符串”,但在您的示例中,如果给定的数字不存在,则将其添加到列表中。
(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”。