scheme - 截断(受限) Racket 中的列表

标签 scheme lisp racket

我的问题实际上是一个逻辑问题,任务是将列表截断到 Racket 中的给定长度。也就是说,给定一个列表 (A B C),给定长度为 2,我想要一个新列表 (A B)。限制是我们有可用功能的限制列表,我将在下面列出。如果这个问题很简单,我深表歉意,但我遇到了困难,无法计算出必要的顺序。如果有人甚至可以为我指出正确的方向,那就太好了。

函数列表:

  • cons, car, cdr, define, quote, if, cond, else
  • 算术的基本形式(+、-、*、/)
  • 非常基本的测试(基本的数字比较,null?,list?,eq?)

我已经创建了一个返回列表长度的函数,我也知道这需要某种形式的递归。

最佳答案

我不会破坏通过您自己的方式找到答案的乐趣(毕竟您要求指点),所以我会给您一些提示。通过使用递归遍历列表的标准模板(我们处理第一个元素,然后对其余元素调用递归)并构建输出列表(使用 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)

关于scheme - 截断(受限) Racket 中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35122533/

相关文章:

方案的 "expected a procedure that can be applied to arguments"

scheme - Scheme 中的二叉树

lisp - Scheme 可以扩展一个列表作为参数吗?

scheme - 我可以在Scheme 的过程内部定义一个全局变量吗?

Lisp - if 语句各种 Action

namespaces - 在 Racket 中,嵌套函数定义不需要 "local"吗?

racket - 如何构建 # :usage-help string dynamically in racket lang's (command-line . ..) 函数?

stream - 交替两个值

lisp - 作为函数参数传递时如何停止评估 lisp 形式?

lambda - 汽车异常: () is not a pair