Recursion 方案编程:与列表交互时函数中出现违反合同错误
我被指示执行以下操作: (insertBag List Item)——返回一个新的包,该包表示在给定列表中插入给定项的结果Recursion 方案编程:与列表交互时函数中出现违反合同错误,recursion,scheme,racket,Recursion,Scheme,Racket,我被指示执行以下操作: (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 function
;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”和cdr
部件中的2
配对。通过这一小小的更改,您的代码将按预期工作:
(insertBag '(("a" . 2) ("d" . 1) ("c" . 3)) "a")
您好@Óscar López,首先感谢您对案例“a”的帮助,但当我为案例“d”或案例“c”这样做时,我得到以下错误:;项目:未定义;不能在标识符定义之前引用标识符;模块内:顶层;[,bt代表上下文]>@rockyDodgers在insertBag
的最后一行中,您编写了item
而不是item
,修复它,它就会工作;)我正要对此发表评论,这时我看了看我的代码,发现错误=)