【问题标题】:returns the first n of list返回列表的第一个 n
【发布时间】:2013-01-23 21:15:08
【问题描述】:

如何返回列表的第一个n 元素?这是我所拥有的:

(define returns(lambda (list n)
 (cond ((null? list) '())
 (((!= (0) n) (- n 1)) (car list) (cons (car list) (returns (cdr list) n)))
        (else '()))))

例子:

(returns '(5 4 5 2 1) 2)
(5 4)

(returns '(5 4 5 2 1) 3)
(5 4 5)

【问题讨论】:

  • 欢迎来到 SE!请更好地格式化您的问题和可读性。你想完成什么?想要定义一个返回列表中前 N 个元素的过程?
  • 请在发布之前格式化您的代码,我这次修复了它,但实际上,如果您希望人们帮助您,您应该更加小心。

标签: list scheme


【解决方案1】:

您要求take 程序:

(define returns take)

(returns '(5 4 5 2 1) 2)
=> (5 4)

(returns '(5 4 5 2 1) 3)
=> (5 4 5)

这看起来像家庭作业,所以我想你必须从头开始实施它。一些提示,填空:

(define returns
  (lambda (lst n)
    (if <???>                     ; if n is zero
        <???>                     ; return the empty list
        (cons <???>               ; otherwise cons the first element of the list
              (returns <???>      ; advance the recursion over the list
                       <???>))))) ; subtract 1 from n

别忘了测试它!

【讨论】:

  • R5RS 我需要。采取:未定义;无法引用未定义的标识符
  • @New 然后自己实现它,如上所示。我不会这样做,因为这看起来像一个家庭作业,这取决于你。
  • (define (returne list n) (take list n))
  • 你不能在 R5RS 中使用take,按照上面的提示从头开始实现returns
猜你喜欢
  • 2012-04-05
  • 2023-01-10
  • 1970-01-01
  • 1970-01-01
  • 2010-11-27
  • 2011-04-08
  • 1970-01-01
  • 1970-01-01
  • 2012-10-12
相关资源
最近更新 更多