user3400060
user3400060

Reputation: 309

Racket list results if no index element is present

I am trying to modify this program in Racket such that if no index element is present in this list, it should return #f. A little guidance is helpful. Thanks in advance

#lang racket
(define get-nth
  (lambda (index lst)
    (let loop ((index index) (my-list lst))
      (cond ((null? my-list) lst)
            ((= index 0) (car my-list))
            (else (loop (- index 1) (cdr my-list)))))))

(get-nth 4 '(a b))

;#f

Upvotes: 1

Views: 77

Answers (2)

David Merinos
David Merinos

Reputation: 1295

You can forget about the let loop and instead use tail-recursion. The list will be empty if you're trying to get to an index longer than the lenght of the list, therefore, when the list is empty, return false.

#lang racket
(define get-nth
  (lambda (index lst)
      (cond 
        ((empty? lst) #f)
        ((= index 0) (car lst))
        (else (get-nth (- index 1) (cdr lst))))))

Upvotes: 0

Óscar López
Óscar López

Reputation: 236004

Just return #f instead of the list...

(define get-nth
  (lambda (index lst)
    (let loop ((index index) (my-list lst))
      (cond ((null? my-list) #f)
            ((= index 0) (car my-list))
            (else (loop (- index 1) (cdr my-list)))))))

Because now we don't have to "remember" the original input list, we can simplify things and eliminate the named let, like this:

(define get-nth
  (lambda (index lst)
    (cond ((null? lst) #f)
          ((= index 0) (car lst))
          (else (get-nth (- index 1) (cdr lst))))))

Upvotes: 1

Related Questions