[Haskell-beginners] Newbie question about function type constraints

Harald Bögeholz bo at ct.de
Thu Sep 22 14:08:56 UTC 2016


Am 22.09.16 um 15:19 schrieb Lai Boon Hui:
> Hi, can someone explain to me why i cannot define meanList as:
> 
> meanList :: (Integral a, Fractional b) => [a] -> a
> meanList xs = (sumList xs) / (lengthList xs)
> 
> I want to restrict the function to only accept lists like [1,2,3] and
> return answer 2.0

It will work like this:

meanList :: (Integral a, Fractional b) => [a] -> b
meanList xs = fromIntegral (sumList xs) / (lengthList xs)

You probably meant -> b in the type signature, that was a typo.

And you need to insert fromIntegral to convert to Fractional before you
can divide. Now that I see it I am beginning to wonder why it works,
though, because I was just about to insert another fromIntegral before
lengthList ...


> sumList :: (Num a) => [a] -> a
> sumList [] = 0
> sumList (x:xs) = x + (sumList xs)
> 
> lengthList :: (Num a) => [t] -> a
> lengthList [] = 0
> lengthList (_:xs) = 1 + (lengthList xs)

Hope this helps


-- 
Harald Bögeholz    <bo at ct.de> (PGP key available from servers)
Redaktion c't      Tel.: +49 511 5352-300  Fax: +49 511 5352-417

                   int f[9814],b,c=9814,g,i;long a=1e4,d,e,h;
                   main(){for(;b=c,c-=14;i=printf("%04d",e+d/a),e=d%a)
                   while(g=--b*2)d=h*b+a*(i?f[b]:a/5),h=d/--g,f[b]=d%g;}
                                                          (Arndt/Haenel)

                   Affe Apfel Vergaser

/*Heise Medien GmbH & Co. KG * Karl-Wiechert-Allee 10 * 30625 Hannover
Registergericht: Amtsgericht Hannover HRA 26709
Persönlich haftende Gesellschafterin: Heise Medien Geschäftsführung GmbH
Registergericht: Amtsgericht Hannover, HRB 60405
Geschäftsführer: Ansgar Heise, Dr. Alfons Schräder*/


More information about the Beginners mailing list