[Haskell-beginners] Why the length function I wrote has such a
type signature?
amazingjxq
amazingjxq at gmail.com
Thu Nov 11 03:55:20 EST 2010
myLength :: [a] -> Int
This is the first type signature I wrote. And I changed the Int into Num
after
ghci tell me it's wrong. This type signature still not work. But the
standard length
function's type signature is this:
length :: [a] -> Int
I think my type signature is right but it's not. And I can not find the
reason.
2010/11/11 Chaddaï Fouché <chaddai.fouche at gmail.com>
> On Thu, Nov 11, 2010 at 9:24 AM, 贾旭卿 <amazingjxq at gmail.com> wrote:
> > This is exercise 3.1 of Real World Haskell. I have my length function
> like
> > this:
> >
> > myLength [] = 0
> > myLength (_:xs) = 1 + (myLength xs)
> >
> > And I assumed the type signature is like this:
> > mylength :: [a] -> Num
> >
> > But when I wrote this into the file and reloaded it into ghci, there is
> an
> > error.
> >>
> >> The type signature for `mylength' lacks an accompanying binding
> >> Failed, modules loaded: none.
> >
> >
> > And the type signature given by ghci is
> >>
> >> myLength :: (Num t1) => [t] -> t1
> >
> > So how can I modify the function to have a type signature like the first
> > one?
>
> You can't, since Num isn't a type, it's a typeclass.
>
> > myLength :: (Num b) => [a] -> b
>
> means that myLength takes a list of any type and can return any type
> that is an instance of Num (Num being the typeclass of numbers, that
> means that you can do most things you do on numbers, adding them,
> multiplying them, and so on...).
>
> If you want a simpler type signature, you could use :
>
> > myLength :: [a] -> Int
>
> or
>
> > myLength :: [a] -> Integer
>
> since Int (32 or 64 bits integer) and Integer are real type that are
> instances of the Num typeclass.
>
> --
> Jedaï
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20101111/19af372b/attachment.html
More information about the Beginners
mailing list