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

来源:互联网 发布:win10磁盘优化闪退 编辑:程序博客网 时间:2024/04/29 16:42

问题描述

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得到列表。
间接实现题目。

1 0
原创粉丝点击