开发者

Only by using cons car cdr

开发者 https://www.devze.com 2023-02-06 06:55 出处:网络
开发者_开发百科How do I get elements from 2nd to 7th from a list, using only the following three functions:
开发者_开发百科

How do I get elements from 2nd to 7th from a list, using only the following three functions:

  • cons
  • car
  • cdr

Example;

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

Thanks.


> (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)


My solution. You might want to initialize the acumulator ( acum ) with 1, and/or use >= and <=. You provided no output.

(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))

Sample output

> (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)

And if you're bothered by the append showing there you could replace it with your own using cons, cdr, car

(define (my-append l1 l2)
    (if (null? l1)
      l2
      (cons (car l1) (my-append (cdr l1) l2))))

To also get rid of the set! so we'll be more in the bounds of functional programming (not tested):

(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))
0

精彩评论

暂无评论...
验证码 换一张
取 消