首页 > 解决方案 > 方案编程:与列表交互时函数中的合同违反错误

问题描述

我被指示执行以下操作: ( 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。我会很感激一些帮助!谢谢!>

标签: recursionschemeracket

解决方案


示例输入存在问题,您必须在点之间写空格:'("a".2)是一个列表,其中"a"0.2作为其元素,而在部分和部分中'("a" . 2)是一cons对。通过这个小改动,您的代码将按预期工作:"a"car2cdr

(insertBag '(("a" . 2) ("d" . 1) ("c" . 3)) "a")

推荐阅读