rockyDodgers
rockyDodgers

Reputation: 61

Scheme Programming: Contract Violation Error in Function when interacting with List

I am instructed to perform the following: ( insertBag List Item ) -- return a new bag that represents the result of inserting the given item in the given list

;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

However, I get the following error:

; +: contract violation
;   expected: number?
;   given: '(0.2)
;   argument position: 2nd
; [,bt for context]

Please note that I was instructed to not use lambda. I would appreciate some help! Thank you! >

Upvotes: 0

Views: 64

Answers (1)

Óscar López
Óscar López

Reputation: 236004

There's a problem with the sample input, you must write spaces between the dots: '("a".2) is a list with "a" and 0.2 as its elements, whereas '("a" . 2) is a cons pair with "a" in the car part and 2 in the cdr part. With this little change, your code will work as expected:

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

Upvotes: 1

Related Questions