[racket] Find nth term of a List

From: Todd O'Bryan (toddobryan at gmail.com)
Date: Tue Sep 25 22:25:25 EDT 2012

Well, I know how I'd do it, but I don't think your professor is
teaching you the design recipe or templates, so I'm not sure how to
help you without giving away the answer.

Here's a hint. Most numbers involving natural numbers (0, 1, 2, 3,
...) have the following form:

(define f
  (lambda (n)
    (if (= n 0) base-case (do-something-to (f (- n 1)))))

Since zero is the base case, the only way you can get there is to
subtract. The tricky part is figuring out what you have to do to the
(f (- n 1)) and how to handle any other arguments to the function.

So, looking at your test cases, (getNth 3 '(a b c d e)) will probably
change into (getNth 2 ...) where you have to fill in the ... with
something that makes the expressions equivalent and you might have to
do some manipulating of the result.

Good luck!


On Tue, Sep 25, 2012 at 9:08 PM, Ashley Fowler
<afowler2 at broncos.uncfsu.edu> wrote:
> I need to make a function that finds the nth term of a list
> Hence (getNth N LS)
>
> Examples of use:
> (getNth 0 '(a b c)) 		==> a
> (getNth 3 '(a b c d e)) 	==> d
> (getNth 3 '(a b c)) 		==> error
>
>
> so far I have
>
> (define getNth (lambda (N LS)
>                    (if (eq? N 0)(car LS)
>
> which only includes the "base case". I need help on how to create this
> function. Any ideas?
>
> ____________________
>   Racket Users list:
>   http://lists.racket-lang.org/users
>

Posted on the users mailing list.