解析列表并生成该结构

时间:2010-05-10 15:22:29

标签: scheme

;; structure representing homework points
;; nr: number - the number of the homework
;; points: number - the number of points reached
(define-struct homework (nr points))



;; parse-homework: (list of number pairs) -> (list of homework)
;; The procedure takes a list of number pairs and produces a list of homework     structures
;; Example: (parse-homework (list (list 1 6) (list 2 7) (list 3 0))) should produce  (list (make-homework 1 6) (make-homework 2 7) (make-homework 3 0)) 

(define (parse-homework homework-entries) 
  (if (and (= (length (first homework-entries) 2))(= (length (parse-homework (rest homework-entries)) 2)))
    (make-homework (first homework-entries) (parse-homework (rest homework-entries)))
    (error 'Non-valid-input "entered list is not of length two"))

  )        


(parse-homework (list (list 1 6) (list 2 7) (list 3 0))) 

此代码产生错误长度:期望1参数,给定2 :(列表1 6)2

我非常感谢你能给我的每一个解释,让你参与这个计划......

非常感谢

1 个答案:

答案 0 :(得分:1)

你的错误(见下文)

(define (parse-homework homework-entries) 
   (if (and (= (length (first homework-entries) 2))  ;; <---- Parens wrong here
            (= (length (parse-homework (rest homework-entries)) 2)))  ;; <---- ... and here 
    (make-homework (first homework-entries) (parse-homework (rest homework-entries)))
    (error 'Non-valid-input "entered list is not of length two"))

)      

你需要用length函数调用=函数,(= (length (first homework-entries)) 2) 函数有两个参数:

homework-entries

同样适用于其他标记线。

编辑解析家庭作业列表时,请考虑:

  • 您何时解析null?的所有元素?即,你何时必须停止递归? (parse-homework)错误说明了一切:输入列表已用完。
  • 根据您的示例,将(define (parse-homework-item item) ;; Parse a single homework item, returning an instance of the ;; Homework type for it. ...) (define (parse-homework list-of-items) ;; Loop over the elements of list-of-items, processing each in turn ;; using parse-homework-item. Collect each result object into a list ;; which is returned as final result. ...) 应用于项目列表的预期结果是什么?您实际上并没有产生有意义的结果。

尝试将问题分解为更小的部分:

{{1}}