user3400060
user3400060

Reputation: 309

Call a method from a method

I am pretty new to Racket. I am trying to write a program to return an index element in the list else, return the entire list. I have two separate methods: One recursive method to give index elements of the list if present else give the entire list. However, calling one method from the other is giving me error. Can someone please guide me how I can change this program to give me the whole list if none of the index elements are present? For example this call should give me the entire list

(get-nth 2 '(a b)) ; ==> a b

#lang racket
(define get-nth
  (lambda (index lst)
    (if (= index 0)            ; when index is zero
        (car lst)              ; return the first element
        (get-nth (- index 1)   ; else recurse with the decrement of index
                 (cdr lst))))) ; and all but the first element (the rest) of lst
;; test

Thanks in advance,

Upvotes: 1

Views: 127

Answers (1)

Óscar López
Óscar López

Reputation: 236122

For this to work, you'll have to store the original list somewhere. To avoid unnecessary helper functions, we can use a named let to implement iteration and leave alone the original lst for the case when we have to return it. And of course, we have to test for the case when we run out of elements because the given index is outside the list. This is what I mean:

(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)))))))

For example:

(get-nth 0 '(a b))
=> 'a

(get-nth 2 '(a b)) 
=> '(a b)

Upvotes: 1

Related Questions