Brian Hulley brianh at metamilk.com
Thu Jun 22 15:36:11 EDT 2006

```Sara Kenedy wrote:
> Hello all,
>
> Now I am trying with the function of polymorphic type: This function
> returns the Nth element of list with type a. I try it as below.
>
> getNthElem :: Int -> [a] -> Maybe a
> getNthElemt _ [] = Nothing
> getNthElem 0 _ = Nothing
> getNthElem n s
>> n > length s = Nothing
>> otherwise = Just ((drop (n-1) (take n s))!!0)
>
>> getNthElem 2 ["a","b","c"]
> Just "b"
>
> However, I do not satisfy with this function because I want to return
> the Nth element of type a, not (Maybe a). For example, I want this
> function:
> getNthElem :: Int -> [a] ->  a
>
> But, I do not know how to define the empty element of type a.
>
> getNthElemt _ [] = ????
> getNthElem 0 _ =  ????
>
> a lot.

You might find it's always a lot easier to start counting from zero rather
than 1, so that "a" is the 0th element, "b" is the 1st element etc. Just
like a building with 2 floors has a ground floor and a first floor, and if
you want to find what day of the week it is in 46 days from today you just
use (today + 46) `mod` 7 instead of (((today - 1) + 46) `mod` 7) + 1

That aside, why not just throw an error when the function is called with an
index that's out of range?

getNthElemt _ [] = error "getNthElemt"

Regards, Brian.
--
Logic empowers us and Love gives us purpose.
Yet still phantoms restless for eras long past,
congealed in the present in unthought forms,
strive mightily unseen to destroy us.

http://www.metamilk.com

```