只能使用cons car cdr

时间:2011-01-25 00:47:06

标签: list functional-programming scheme

如何从列表中获取第2到第7个元素,仅使用 以下三个函数:

  • cons
  • car
  • cdr

实施例

> (two-to-seven (list 8 9 5 1 0 3 6 2 4))
> (9 5 1 0 3 6)

感谢。

2 个答案:

答案 0 :(得分:3)

> (define (t2s xs)
    (cons (car (cdr xs)) (cons (car (cdr (cdr xs))) (cons (car (cdr (cdr (cdr xs)))) (cons (car (cdr (cdr (cdr (cdr xs))))) (cons (car (cdr (cdr (cdr (cdr (cdr xs)))))) (cons (car (cdr (cdr (cdr (cdr (cdr (cdr xs))))))) (list))))))))
> (t2s (list 8 2 5 4 0 3 6 1 1))
(2 5 4 0 3 6)

答案 1 :(得分:0)

我的解决方案。您可能希望使用1初始化累加器(acum),和/或使用>=<=。你没有提供输出。

(define (test-get start stop tlst)
(define acum 0)
(define (get-elems lst)
    (cond ((null? lst) empty)
          ((and (symbol? (car lst))
                (< acum stop)
                (> acum start))
                    (set! acum (+ 1 acum)) 
                    (cons (car lst) (get-elems (cdr lst))))
          ((symbol? (car lst)) 
                (set! acum (+ 1 acum))
                (get-elems (cdr lst)))
          (else (append (get-elems (car lst)) (get-elems (cdr lst))))))

  (get-elems tlst))

示例输出

> (test-get 0 3 '(a (b) (c (d)) e (((f))) (h (i (j))) (k l)))
(b c)
> (test-get 2 6 '(a (b) (c (d)) e (((f))) (h (i (j))) (k l)))
(d e f)
> (test-get 2 7 '(a (b) (c (d)) e (((f))) (h (i (j))) (k l)))
(d e f h)

如果您对显示在那里的append感到困扰,可以使用conscdrcar

将其替换为您自己的(define (my-append l1 l2) (if (null? l1) l2 (cons (car l1) (my-append (cdr l1) l2))))
set!

为了摆脱(define (test-get start stop tlst) (define (liniarize lst) (cond ((null? lst) empty) ((symbol? (car lst)) (cons (car lst) (liniarize (cdr lst)))) (else (my-append (liniarize (car lst)) (liniarize (cdr lst)))))) (define (take-elems lst acum) (cond ((null? lst) empty) ((and (< acum stop) (> acum start)) (cons (car lst) (take-elems (cdr lst) (+ 1 acum)))) (else (take-elems lst (+ 1 acum))))) (take-elems (liniarize tlst) 0)) ,我们将更多地处于函数式编程的范围内(未经测试):

{{1}}