您的位置:首页 > 其它

P18 (**) Extract a slice from a list.

2016-01-17 11:59 302 查看

问题描述

Given two indices, I and K, the slice is the list containing the elements between the I’th and K’th element of the original list (both limits included). Start counting the elements with 1.

sash> (slice '(a b c d e f g h i k) 3 7)
sash> (c d e f g)


解法

递归实现

(define slice
(lambda (ls I K)
(let f ([i 1]
[s ls])
(cond
[(> i K) '()]
[(<= I i K)
(cons (car s) (f (+ i 1) (cdr s)))]
[else (f (+ i 1) (cdr s))]))))


基本思路是:

(1) 索引I之前的元素丢弃;

(2) [I, K]之内的元素累积;

(3) 索引K+1作为递归结束条件。

切片操作是比较常见的操作,可惜r7rs中的
list-copy
只能返回整个列表的副本,没有提供其他重载。但
string-copy
提供了多个重载。这样我们可以:

(1) 将list转化为string:list->string;

(2) string-copy得到新的字符串;

(3) string->list得到列表。

间接实现题目。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lisp scheme