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

问题描述

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值