首页 文章

截断(约束)Racket中的列表

提问于
浏览
1

我的问题实际上是逻辑之一,任务是将一个列表截断到球拍中的给定长度 . 也就是说,给定一个列表(A B C),给定长度为2,我想要一个新的(A B)列表 . 限制因素是我们有一个受限制的可用功能列表,我将在下面列出 . 如果这个问题很简单,我很难道歉,但是我遇到了困难,并且无法确定必要的顺序 . 如果有人能够指出我正确的方向,那将是美好的 .

功能列表:

  • cons,car,cdr,define,quote,if,cond,else

  • 算术的基本形式(, - ,*,/)

  • 非常基本的测试(基本数字比较,null ?, list?,eq?)

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

1 回答

  • 1

    我赢了't spoil the fun of reaching the answer by your own means (after all you asked for pointers), so I'给你一些提示 . 通过使用标准模板递归遍历列表(我们处理第一个元素,然后使用其余元素调用递归)和构建输出列表(使用 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)
    

相关问题