[Haskell-cafe] Polymorphic type
sarakenedy at gmail.com
Thu Jun 22 21:27:25 EDT 2006
Thanks all. I think for my function, I only need to throw an error
message for the out of range index. But through this, I know more some
ways to deal with the polymorphic type.
On 6/22/06, Brian Hulley <brianh at metamilk.com> wrote:
> 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 _ = ????
> > If you have some ideas about this, please give me some clues. Thanks
> > 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.
More information about the Haskell-Cafe