View Single Post
Old Oct 17th, 2006, 6:57 AM   #2
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5 Arevos is on a distinguished road
My haskell isn't great, but you need to approach this problem from a recursive standpoint. Firstly, consider the limiting case; the set of arguments that will stop the recursion.

In this case, if n is 0, then all we have to do is return the beginning of the list (assuming that you want the first element to have an index of 0, rather than 1):
getelem 0 x:xs = x
So far so good? Now that the limiting case has been created, we want the general case. We want to define the general case in terms of itself, in a way that approaches the limiting case. So first, we want n to approach 0. Second, we want the list to be cut until the head of the list is the element we want. To put this in code:

getelem n x:xs = getelem (n - 1) xs

So your final function definition should look like:
getelem :: Integer -> [a] -> a
getelem 0 x:xs = x
getelem n x:xs = getelem (n - 1) xs
Note that I do not currently have access to a Haskell compiler, but hopefully my code should be syntaxically correct.

Last edited by Arevos; Oct 17th, 2006 at 7:40 AM. Reason: getelem 1 should be getelem 0
Arevos is offline   Reply With Quote