This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

Which version of this function is best?

1 post · 4056 views

So I've finished SICP videos and I noted that sometimes DEFINE is used twice to package a function within a function. I know that Scheme demands tail recursion. So I'd like to get some thoughts on the two versions of a function to get the first n many items. The second is mine. I thought the first might not be ideal since it is not really tail call optomized. The user dsm there has many many answers to questions. I'm new to Scheme and he seems to be well educated in it.

Is my function gaining anything by calling the recursion last at the expense of function length?
Also is it inefficient to nest function definitions like that? Does the second function get redefined each time the outside function is called or does it get stored once when compiled?
;; Function by user "dsm" on stackoverflow
(define get-n-items
    (lambda (lst num)
        (if (> num 0)
            (cons (car lst) (get-n-items (cdr lst) (- num 1)))
            '()))) ;'


;; Return first n number of items
(define (get-n-items num lst)
  (define (loop lst num results)
    (if (< num 1)
        (reverse results)
        (loop (cdr lst) (- num 1) (cons (car lst) results))))
  (loop lst num '()))