我有值列表,并希望从中获取前x个值并创建(列表(第一个x值的列表)(下一个x值的列表),依此类推,直到此列表变空...)。
例如,给定此列表:(list "a" "b" "c" "d" "e" "f" "g" "h" "t")
返回此:(list (list a" "b" "c") (list "d" "e" "f") (list "g" "h" "t"))
提前致谢:)
答案 0 :(得分:1)
记住列表的数据类型是什么。你的班级可能会做类似的事情:
;; A IntegerList is one of:
;; - '()
;; - (cons Integer IntegerList)
鉴于此,您的模板应该反映这种结构。我将解决基本情况(我们想要将整数列表转换为一个整数的列表。
首先,我将1List
数据类型定义为:
;; a 1List is:
;; - (cons Integer '())
接下来,该功能的目的陈述和签名将是:
;; Takes a list of integers and returns a list of 1Lists of the same integers
;; IntegerList -> 1List
(define (make-1list lst)
...)
好的很酷。现在我们需要测试用例:
(check-expect (make-1list (list 1 2 3)) (list (list 1) (list 2) (list 3)))
(check-expect (make-1list (list)) (list))
(check-expect (make-1list (list 42)) (list (list 42)))
最后,我可以制作我的模板:
(define (make-1list lst)
(cond [(null? lst) ...]
[else ... (first lst) ... (rest lst) ...]))
(请注意,首先制作一些模板有助于指导您需要的测试。)
最后,我们可以填写我们的代码:
(define (make-1list lst)
(cond [(null? lst) '()]
[else (cons (list (first lst)) (make-1list (rest lst)))]))
最后,示例也是测试,所以我们只需要运行它们以确保一切正常。
现在,既然您想要3List
而不是1List
,那么您是否看到如何按照此配方来解决问题?
遵循此模式应该可以帮助您将问题分解为更小的步骤。祝你好运。
答案 1 :(得分:0)
完成此任务的更好方法是使用累加器和放大器。递归。