0

I am picking up scheme as a way to learn recursive and I found it very good for me:D But now, I have a question. How would i make a function called thirds that picks one element and skips 2 and repeats the process over. So it returns a new list with the first element from, every triple of elements For example (thirds '(a b c d e f g h)) should return (a d g)

(DEFINE (thirds lst)
 (COND
   ((NOT(list? lst)) (newline) "USAGE: (thirds [list])")
   ((NULL? lst) lst)
   ((NULL? (CDR lst)) (CAR lst))
   (ELSE (CONS (CAR lst) (thirds (CDR(CDR(CDR lst)))) )) ))

thats the code i have tried but not any real luck.. any help?

R Sahu
  • 204,454
  • 14
  • 159
  • 270
Harold B
  • 23
  • 8
  • You're missing a base case. What if you list is two elements long? – WorBlux Apr 07 '14 at 03:06
  • This question has been answered _several times_ the last couple of days, [here](http://stackoverflow.com/a/22827083/201359)'s my own attempt. I guess you guys are taking the same course... – Óscar López Apr 07 '14 at 03:16

1 Answers1

0

There's another way to do this, which is to create a helper function and pass along an index.

(define (thirds L)
 (thirds-helper L 0))

(define (thirds-helper L i)
 (cond ((null? L) '())
       ((= 0 (modulo i 3)) 
        (cons (car L) 
              (thirds-helper (cdr L) (+ i 1))))
       (else (thirds-helper (cdr L) (+ i 1)))))

Exercise for the reader. Can you modify this to pick out any given nth values of a list?

WorBlux
  • 1,423
  • 11
  • 20