如何在方案中获取列表的一部分(子列表)? [英] How do I take a slice of a list (A sublist) in scheme?
本文介绍了如何在方案中获取列表的一部分(子列表)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出一个列表,我如何选择一个包含原始列表切片的新列表(给出偏移量和元素数量)?
Given a list, how would I select a new list, containing a slice of the original list (Given offset and number of elements) ?
到目前为止,很好的建议.在其中一个SRFI中没有指定内容吗?这似乎是一件非常基本的事情,所以令我惊讶的是我需要在用户领域实现它.
Good suggestions so far. Isn't there something specified in one of the SRFI's? This appears to be a very fundamental thing, so I'm surprised that I need to implement it in user-land.
推荐答案
以下代码将满足您的要求:
The following code will do what you want:
(define get-n-items
(lambda (lst num)
(if (> num 0)
(cons (car lst) (get-n-items (cdr lst) (- num 1)))
'()))) ;'
(define slice
(lambda (lst start count)
(if (> start 1)
(slice (cdr lst) (- start 1) count)
(get-n-items lst count))))
示例:
> (define l '(2 3 4 5 6 7 8 9)) ;'
()
> l
(2 3 4 5 6 7 8 9)
> (slice l 2 4)
(3 4 5 6)
>
这篇关于如何在方案中获取列表的一部分(子列表)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文