Which version of this function is best?

Discussion of Scheme and Racket

Which version of this function is best?

Postby Pixel_Outlaw » Fri Jan 30, 2015 12:29 am

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?

Code: Select all
;; 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 '()))
Pixel_Outlaw
 
Posts: 43
Joined: Mon Aug 26, 2013 9:24 pm

Return to Scheme

Who is online

Users browsing this forum: No registered users and 2 guests