recursionracketracket-student-languages

Stuck while writing a recursion function in racket beginner language?


So recently I learned recursive function and I am trying some exercise then I am just stuck.

Question is list-nth-item, that consumes a list, (lst), and a natural number, (n), and produces the n-th element in lst if exists, otherwise the function produces false. Note that the first item is in index 0. For example: (list-nth-item (list 1 2 3) 0)produces 1

Here is my code

     ;;list-nth-item consumes list and a natural number
     ;;and produces the n-th element in the list or false
     ;;list-nth-item: List Nat -> (Anyof Any false)
    (define (list-nth-item lst n)
          (cond
            [(empty? lst)false]
            [(= n 0)(first lst)]
            [else ????]))


         (list-nth-item (list 1 2 3)2)--> should produce 3

I know thus is not a proper recursion, also when n = 0 it should produce first number in the list example (list-nth-item (list 1 2 3)0)should give1. I am new to this just not getting how to form a recursion.


Solution

  • Think of list as a conveyor belt: you check if you arrived to your item (using you first case (= n 0)), and if not (else case) you just shift the belt by taking the tail of list (using cdr function) and repeating the process again.

    This can be done like following:

    (define (list-nth-item lst n)
      (cond
        [(empty? lst) #f]
        [(zero? n) (car lst)]
        [else (list-nth-item     ; <-- repeats the process
               (cdr lst)         ; <-- shifts the "belt"
               (sub1 n))]))      ; <-- updates the number of steps to go
    

    PS: this is already done by list-ref function.