[racket] Find nth term of a List

From: Marco Morazan (morazanm at gmail.com)
Date: Wed Sep 26 10:31:57 EDT 2012

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

A couple of observations:

1. Is eq? the most natural way to test the equality of numbers? (minor quibble)

2. You need to process two pieces of (recursively defined) data of
arbitrary size: a natural number and a list. Your code suggests you
have decided to write this function as you would any function that
processes a natural number. Is this the best choice? What will happen
if N is 0 and the list is empty?

Others have pointed you to references in which you will discover that
you ought to write this function analyzing the different possible
combinations of the input data. Specifically, a natural number can be
0 or not be zero while a list can be empty or not empty. This gives
you four possible scenarios:

N is 0 and LS is empty
N 0 and LS is not empty
N is not 0 and LS is empty
N is not 0 and LS is not empty

What should your code do for each of these?

I hope that helps.

-- 

Cheers,

Marco

Have a´¨)
¸.·´¸.·*´¨) ¸.·*¨)
(¸.·´ (¸.·´ * wonderful day! :)


Posted on the users mailing list.