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得到列表。
间接实现题目。
相关文章推荐
- 用Python编写一个简单的Lisp解释器的教程
- Windows下Lisp环境配置
- 我以为的函数式编程
- authentication password与scheme区别
- 在Ubuntu12.04上的Common Lisp开发环境配置
- OSX 10.09上的common lisp环境搭建
- emacs学习
- MIT-scheme写的一个数据处理程序
- authentic Arizona Cardinals jerseys b2bjersey.com 8n
- 创造者的鉴赏力[转]
- 你需要掌握的三种编程语言
- Common Lisp 学习书目
- Beginning of Learning LISP.
- Begining Of Learning LISP (2)
- 毕业三年,新目标
- The hundred-year language - Paul Graham
- 编程起步
- 元编程(metaprogrammming)的艺术:元编程介绍
- URI vs URL vs URN
- Tomcat6配置SSL的方法