截断(受限)球拍中的列表
Truncating a list in (constrained) Racket
我的问题实际上是一个逻辑问题,任务是将列表截断到球拍中的给定长度。也就是说,给定一个列表 (A B C),给定长度为 2,我想要一个新列表 (A B)。限制是我们有可用功能的限制列表,我将在下面列出。如果这个问题很简单,我深表歉意,但我遇到了困难,无法计算出必要的顺序。如果有人甚至可以为我指出正确的方向,那就太好了。
函数列表:
- cons, car, cdr, define, quote, if, cond, else
- 算术的基本形式 (+, -, *, /)
- 非常基本的测试(基本数值比较,null?,list?,eq?)
我已经创建了一个 returns 列表长度的函数,我也知道这需要某种形式的递归。
我不会破坏通过你自己的方式找到答案的乐趣(毕竟你要求指点),所以我会给你一些提示。这个问题是通过使用标准模板递归遍历列表(我们处理第一个元素然后用其余元素调用递归)并构建输出列表(使用cons
)解决的,记下它因为你会反复使用它。只需填空:
(define (truncate lst n)
(cond ((null? lst) ; if the list is empty then n is invalid
<???>) ; and you should signal an error
((= n <???>) ; if n is zero we're done
<???>) ; return an empty list
(else ; otherwise build the output list
(cons <???> ; cons the first element in the list and call the recursion
(truncate <???> <???>))))) ; move to the rest of the list, decrement n
第一个条件是可选的,如果您可以假设要截断的元素数量是正确的,只需将其删除即可。它应该按预期工作:
(truncate '(A B C) 2)
=> '(A B)
我的问题实际上是一个逻辑问题,任务是将列表截断到球拍中的给定长度。也就是说,给定一个列表 (A B C),给定长度为 2,我想要一个新列表 (A B)。限制是我们有可用功能的限制列表,我将在下面列出。如果这个问题很简单,我深表歉意,但我遇到了困难,无法计算出必要的顺序。如果有人甚至可以为我指出正确的方向,那就太好了。
函数列表:
- cons, car, cdr, define, quote, if, cond, else
- 算术的基本形式 (+, -, *, /)
- 非常基本的测试(基本数值比较,null?,list?,eq?)
我已经创建了一个 returns 列表长度的函数,我也知道这需要某种形式的递归。
我不会破坏通过你自己的方式找到答案的乐趣(毕竟你要求指点),所以我会给你一些提示。这个问题是通过使用标准模板递归遍历列表(我们处理第一个元素然后用其余元素调用递归)并构建输出列表(使用cons
)解决的,记下它因为你会反复使用它。只需填空:
(define (truncate lst n)
(cond ((null? lst) ; if the list is empty then n is invalid
<???>) ; and you should signal an error
((= n <???>) ; if n is zero we're done
<???>) ; return an empty list
(else ; otherwise build the output list
(cons <???> ; cons the first element in the list and call the recursion
(truncate <???> <???>))))) ; move to the rest of the list, decrement n
第一个条件是可选的,如果您可以假设要截断的元素数量是正确的,只需将其删除即可。它应该按预期工作:
(truncate '(A B C) 2)
=> '(A B)