[Haskell-cafe] Polymorphic type

minh thu noteed at gmail.com
Thu Jun 22 14:33:06 EDT 2006


2006/6/22, Sara Kenedy <sarakenedy at gmail.com>:
> 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 _  =  ????
>
>  If you have some ideas about this, please give me some clues. Thanks a lot.
>

hi,
precisely, you want to return an "a" only when there is one
accordingly to your above code. the only way to handle this without
resorting to [] or Nothing to say there is no such value is to use
error or default value.

infact, ask yourself, what do you want ?
>getNthElem 5 ["a","b","c"]
or
>getNthElem 0 ["a","b","c"]
or
>getNthElem (-1) ["a","b","c"]
do you want
> "a"
> []
> Nothing
> "wrong"
or raise an exception (i.e. you use the "error" function) ?

once you know what you want, you can code it.

note, i think your 'take" is unnecessary here
>                | otherwise     = Just ((drop (n-1) (take n s))!!0)
also
you can use
>                | otherwise = Just (n!!some_value) -- :)
this is where you see that the function you're trying to write is
really close of
> (!!)

cheers,
mt


More information about the Haskell-Cafe mailing list