recursion - 方案编程:与列表交互时函数中的合同违反错误
问题描述
我被指示执行以下操作: ( 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")
推荐阅读
- python - 从 spotipy 中的 id 获取曲目的名称
- list - 在 Haskell 中按每个字符拆分 [Char]
- winapi - 获取任何给定 UNC 文件夹路径(包括 NAS)和任何每用户重定向的 FinalPath
- regex - 如何使用正则表达式获取部分数据
- jdbc - Splunk 未显示 Snowflake 中的所有数据库
- javascript - Web 开发者训练营:使用 JS 迭代数组
- r - 在循环中填充空向量
- sql - SQL通过数据分组将数据复制到新表添加序列
- python - 警告:错误的管道:没有元素“cameracalibrate”
- powershell - 使用 powershell 进行高级文件搜索