round returns an Integral type, but sqrt expects a Floating type<div><div><br></div><div><div>Prelude> :t sqrt</div><div>sqrt :: (Floating a) => a -> a</div><div>Prelude> :t round</div><div>round :: (RealFrac a, Integral b) => a -> b</div>
<div>Prelude></div><div><br></div><div>Haskell's numeric type classes can be intimidating for beginners, but it basically means you are combining floating point numbers with integer numbers, and you must convert these numbers to the same type (just as in C# or other languages, so that are aware of possible unwanted numerical effects).</div>
<div><br></div><div>You can use functions like fromIntegral and realToFrac to convert numbers.</div><div><br></div><div>So try this</div><div><br></div><div>thing n = n + fromIntegral ( round(sqrt n) )<br></div><div><br></div>
<div>You can also get rid of the parentheses like this:</div><div><br></div><div><div>thing n = n + fromIntegral $ round $ sqrt n<br></div><div><br></div><div><br></div></div><div class="gmail_quote">On Thu, Mar 26, 2009 at 11:01 PM, Ivan Moore <span dir="ltr"><<a href="mailto:ivan.r.moore@gmail.com">ivan.r.moore@gmail.com</a>></span> wrote:<br>
<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">Hi all,<br>
<br>
consider this very small function:<br>
<br>
thing n = n + round(sqrt n)<br>
<br>
It loads into ghci with no warnings. When I try to run "thing 10" I get:<br>
<br>
*Main> :load c:\temp\statictype.hs<br>
[1 of 1] Compiling Main ( C:\temp\statictype.hs, interpreted )<br>
Ok, modules loaded: Main.<br>
*Main> thing 10<br>
<br>
<interactive>:1:0:<br>
Ambiguous type variable `t' in the constraints:<br>
`Integral t' arising from a use of `thing' at <interactive>:1:0-7<br>
`RealFrac t' arising from a use of `thing' at <interactive>:1:0-7<br>
`Floating t' arising from a use of `thing' at <interactive>:1:0-7<br>
Probable fix: add a type signature that fixes these type variable(s)<br>
<br>
I have tried to add various type signatures (without really knowing<br>
what I'm doing!) and haven't been able to get it to work.<br>
<br>
I am confused about a few things related to this:<br>
(a) what type signature fixes it and why it needs any help - it looks<br>
like the sort of thing that type inference shouldn't need any help<br>
with<br>
(b) it looks like a runtime type error and I thought you didn't get<br>
runtime type errors in Haskell<br>
(c) if I substitute 10 for n and do "10 + round(sqrt 10)" I get the<br>
expected answer 13<br>
<br>
any help most welcome.<br>
<br>
cheers,<br>
<br>
Ivan<br>
_______________________________________________<br>
Beginners mailing list<br>
<a href="mailto:Beginners@haskell.org">Beginners@haskell.org</a><br>
<a href="http://www.haskell.org/mailman/listinfo/beginners" target="_blank">http://www.haskell.org/mailman/listinfo/beginners</a><br>
</blockquote></div><br></div></div>