Search code examples
listrecursionschemeracketradix

Using recursion to getNth position for Racket


I have to write a recursive call in Racket that allows us to get the Nth position of a given list. for example (getNth 3 '(1 2 3 4)) should return back 4 and if the list is empty or if the position is non existent then return and empty list.

this is my code:

(define getNth
   (lambda (ls)
     (if (= ls null?) 1
         (getNth ls(append '(car ls)(cdr ls)))))) 

getting this error: getnth: arity mismatch; the expected number of arguments does not match the given number expected: 1 given: 2 arguments...: 4 ()

if you need the recursive statement here it is:

base case-getNth N LS) = (), if LS = null

recursive call -(getNth N LS) = (getNth N (append '(car LS)(cdr LS))), if N >= 1

im getting stumped I dont know how to implement this one.


Solution

  • Assuming your getNth can revieve a "N" from a list (rather than a fixed N i.e. get3rd), your are indeed missing an argument:

    (define getNth                     
       (lambda (n list)                   
          (cond ((null? list) '())             
                ((= n 0) (car list))              
                (else (getNth (- n 1) (cdr list))))))
    

    Which basically is until I get to the number I want, decrement the it and "pop" the first element out until the first element of the list is the one I want i.e. the rest of the list.

    Your lambda only takes one argument the way you defined it which is exactly the error message you're having ;)

    I think I appropriately balanced my parenthesis :)

    A trick with recursion: it's generic concept is easy:

    A recusrion is "if a terminal condition occurs, I'm done, return appropriate value. Else, increment the argument toward termination condition and call myself with these new arguments"

    It gets complicated when the termination condition can have exceptions. Because if your can't trivially expressed it as "if this done else redo with increment" you could make mistakes...