<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
</head>
<body bgcolor="#FFFFFF" text="#000000">
<p>Hi,</p>
<p>You can define it, but in practice there is no instance of "a"
that satisfies both constraints: Integral a and Fractional a<br>
> meanList ([1,2,3] :: [Int])<br>
<br>
<interactive>:4:1: error:<br>
• No instance for (Fractional Int) arising from a use of
‘meanList’</p>
<p>> meanList ([1,2,3] :: [Float])<br>
<br>
<interactive>:5:1: error:<br>
• No instance for (Integral Float) arising from a use of
‘meanList’<br>
</p>
<p>What you probably want is:<br>
meanList :: (Integral a, Fractional b) => [a] -> b<br>
meanList xs = fromIntegral (sumList xs) / fromIntegral (lengthList
xs)<br>
</p>
<p>Where we convert from the integral type "a" to the fractional
type "b" before performing the division.</p>
<p>> meanList ([1,2,3] :: [Int])<br>
2.0<br>
</p>
<p>Cheers<br>
Sylvain<br>
</p>
<br>
<div class="moz-cite-prefix">On 22/09/2016 15:19, Lai Boon Hui
wrote:<br>
</div>
<blockquote
cite="mid:CAJdQgg=jJYfdRsq+QfBr1aC-hS1ft9+4Sp4jopoktg=JnDMirg@mail.gmail.com"
type="cite">
<div dir="ltr">
<div>Hi, can someone explain to me why i cannot define meanList
as:</div>
<div><br>
</div>
<div>
<div>meanList :: (Integral a, Fractional b) => [a] -> a</div>
<div>meanList xs = (sumList xs) / (lengthList xs)</div>
</div>
<div><br>
</div>
<div>I want to restrict the function to only accept lists like
[1,2,3] and return answer 2.0</div>
<div><br>
</div>
<div><br>
</div>
<div>sumList :: (Num a) => [a] -> a</div>
<div>sumList [] = 0</div>
<div>sumList (x:xs) = x + (sumList xs)</div>
<div><br>
</div>
<div>lengthList :: (Num a) => [t] -> a</div>
<div>lengthList [] = 0</div>
<div>lengthList (_:xs) = 1 + (lengthList xs)</div>
<div><br>
</div>
<div><br>
</div>
</div>
<br>
<fieldset class="mimeAttachmentHeader"></fieldset>
<br>
<pre wrap="">_______________________________________________
Beginners mailing list
<a class="moz-txt-link-abbreviated" href="mailto:Beginners@haskell.org">Beginners@haskell.org</a>
<a class="moz-txt-link-freetext" href="http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners">http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners</a>
</pre>
</blockquote>
<br>
</body>
</html>