编写一个函数,以一个列表和一个长度作为输入,并返回两个列表:(1)输入列表的第一个长度元素,(2)输入列表的其余部分。提示:使用带有“累加器”参数的助手方法。我被困住了,可能真的需要帮助。
当我尝试做(拆分列表'(a,b,c,d,f) 7)时,我总是会出错,这是一个等于长度的数字,否则任何小于它应该做的事情的数字都会出错:
Argument #1 '()' to 'car' has wrong type (empty-list)
(split-list '(a b c d e f g) 0)应该返回'(() (a b c d e f g))
(split-list '(a b c d e f g) 1)应该返回'((a) (b c d e f g))
(split-list '(a b c d e f g) 3)应该返回'((a b c) (d e f g))
(define (split-list lst length)
(define(split-list-head accum length)
(if (= length 0)
(cdr '(accum))
(cons (car accum) (split-list-head (cdr accum)(- length 1)))
)
)
(define(split-list-tail accum length)
(if (= length 0)
(cons (car accum)(cdr accum))
(split-list-tail (cdr accum)(- length 1))
)
)
(if (eq? length 0)
(append(list (list))(list lst))
(append(list(split-list-head lst length)) (list(split-list-tail lst length)))
)
)发布于 2022-10-10 16:12:01
除非你特别重视GNU计划,否则我会考虑搬到Racket博士那里去。
虽然它是为类似的语言编写的,称为Racket,但可以通过插入第一行#lang scheme来设置为运行vanilla
拉科特博士的优点是它有一个非常好的调试器。
我的代码,开头是#lang行,底部是错误行:
#lang scheme
(define (split-list lst length)
(define(split-list-head accum length)
(if (= length 0)
(cdr '(accum))
(cons (car accum) (split-list-head (cdr accum)(- length 1)))
)
)
(define(split-list-tail accum length)
(if (= length 0)
(cons (car accum)(cdr accum))
(split-list-tail (cdr accum)(- length 1))
)
)
(if (eq? length 0)
(append(list (list))(list lst))
(append(list(split-list-head lst length)) (list(split-list-tail lst length)))
)
)
(split-list '(a b c d e f g) 7)如果我只是运行代码,它会突出显示split-list-tail中的错误,其中car会导致合同违约。它还显示了调用序列。

这可能足以识别错误,但我也可以运行调试器。通过单击“调试”按钮,我将进入调试模式。通过将鼠标指针移动到圆括号上,并右击,我可以启用或禁用此点的暂停--由粉红色圆圈显示。变量显示在右手边。在调试器中运行代码时,变量accum为空,因此car accum失败。

我的建议是,在调用pair?或null?之前,使用accum或null?来测试accum。
发布于 2022-10-18 01:49:52
尝尝这个。它利用了三个累积参数。减法也是一种积累。
(define (split n xs k)
(define (loop xs n k)
(if
(and (> n 0) (not (null? xs)))
(loop (cdr xs) (- n 1)
(lambda (a b) (k (cons (car xs) a) b)))
(k '() xs)))
(loop xs n k))你能看到怎么称呼它吗?
你能解释一下它的工作原理吗?
或者再短一点,
(define (split n xs k)
(define ((+ f a) b) (f (cons (car a) b)))
(define (loop xs n k)
(if
(and (> n 0) (not (null? xs)))
(loop (cdr xs) (- n 1) (+ k xs))
((k '()) xs)))
(loop xs n k))你能找到一种如何调用这个函数的方法吗?我给你个提示,这个函数该怎么做?
(define ((add a) b) (list a b))被召唤吗?
https://stackoverflow.com/questions/74012510
复制相似问题