list - 返回列表的前 n 个

标签 list scheme

如何返回列表的第一个 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)

最佳答案

你要求 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

不要忘记测试它!

关于list - 返回列表的前 n 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14489520/

相关文章:

C# 检查列表中的任何 int 是否与另一个列表中的任何 int 匹配

Python 清除用于 Tkinter 小部件的列表

scheme - 方案中的 n arity zip 函数(apply 和 map 的问题)

lisp - 您将 Scheme 宏用于哪些方面?

algorithm - 在Scheme中将字节字符串转换为Int

python - 从列表写入 CSV,write.row 似乎停在了一个奇怪的地方

arrays - Bash - 如何将列表分配给数组成员

python - 无法为元组列表中的数据返回无

functional-programming - 自学SICP你会用什么语言?

functional-programming - 在Scheme中编写一个自动内存。帮助宏和包装器