; File: take.scm ; Title: Takes the first n elements of a list ; > (take 3 '(a b )) -> (a b) ;> (take 2 '(a b c d)) -> (a b) ;> (take 1 '(a b c)) -> (a) ;> (take 0 '(a b c)) -> () ;;;;;;;;;;;;;;;;;Copies the first n elements in another list ;This function takes(copies) the first n elements from the list L ;> (take 3 '(a b c d e f g)) - > (a b c) ;> (take 1 '(a b c d e f g)) -> (a) (define (take n L) (cond ((or (= n 0) (null? L)) ()) (#t (cons (car L) (take (- n 1) (cdr L)))))) ; Tail-recursive version of above (define (taket n L) (letrec ((taketaux (lambda (n L L2) (cond ((null? L) L2) ; If there's nothing left, just return what we have ;((= n 1) (append L2 (list (car L)))) ; If we only need one more, just add one more. (else (taketaux (- n 1) (cdr L) (append L2 (list (car L))))) ) ))) ; decrement n, tail of L, partially completed list (taketaux n L ()) ; L2 starts empty ))