指示我执行以下操作:(insertBag List Item(--返回一个新的袋子,表示在给定列表中插入给定项目的结果
;Function Two: insertBag
;@Param: List, Item
;@Return: The new bag that represents the result of
;inserting the given item in the given list.
;Important Note: There are two Helper functions for insertBag
;Helper Function One: newPair
;Helper Function Two: addPair
(define (insertBag List Item)
;Check if we have an Empty List
(if (null? List)
(newPair Item)
(if (string=? (car(car List)) Item)
(cons (addPair (car List)) (cdr List))
(cons (car List) (insertBag(cdr List) item))
)
)
)
;Helper Function One: newPair
(define (newPair Item)
(cons Item 1)
)
;Helper Function Two: addPair
(define (addPair List)
(cons (car List) (+ 1 (cdr List)))
)
;Test Run Case for insertBag
(insertBag '(("a".2)("d".1)("c".3)) "a"); Input for A
然而,我得到以下错误:
; +: contract violation
; expected: number?
; given: '(0.2)
; argument position: 2nd
; [,bt for context]
请注意,我被指示不要使用lambda。我很感激你的帮助!非常感谢。>
样本输入有问题,必须在点之间写入空格:'("a".2)
是一个以"a"
和0.2
为元素的列表,而'("a" . 2)
是一对cons
,"a"
在car
部分,2
在cdr
部分。有了这个小小的更改,您的代码将按预期工作:
(insertBag '(("a" . 2) ("d" . 1) ("c" . 3)) "a")