[Haskell-beginners] beginner's type error

Peter Verswyvelen bugfact at gmail.com
Fri Mar 27 08:29:28 EDT 2009


round returns an Integral type, but sqrt expects a Floating type
Prelude> :t sqrt
sqrt :: (Floating a) => a -> a
Prelude> :t round
round :: (RealFrac a, Integral b) => a -> b
Prelude>

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).

You can use functions like fromIntegral and realToFrac to convert numbers.

So try this

thing n = n + fromIntegral ( round(sqrt n) )

You can also get rid of the parentheses like this:

thing n = n + fromIntegral $ round $ sqrt n


On Thu, Mar 26, 2009 at 11:01 PM, Ivan Moore <ivan.r.moore at gmail.com> wrote:

> Hi all,
>
> consider this very small function:
>
> thing n = n + round(sqrt n)
>
> It loads into ghci with no warnings. When I try to run "thing 10" I get:
>
> *Main> :load c:\temp\statictype.hs
> [1 of 1] Compiling Main             ( C:\temp\statictype.hs, interpreted )
> Ok, modules loaded: Main.
> *Main> thing 10
>
> <interactive>:1:0:
>    Ambiguous type variable `t' in the constraints:
>      `Integral t' arising from a use of `thing' at <interactive>:1:0-7
>      `RealFrac t' arising from a use of `thing' at <interactive>:1:0-7
>      `Floating t' arising from a use of `thing' at <interactive>:1:0-7
>    Probable fix: add a type signature that fixes these type variable(s)
>
> I have tried to add various type signatures (without really knowing
> what I'm doing!) and haven't been able to get it to work.
>
> I am confused about a few things related to this:
> (a) what type signature fixes it and why it needs any help - it looks
> like the sort of thing that type inference shouldn't need any help
> with
> (b) it looks like a runtime type error and I thought you didn't get
> runtime type errors in Haskell
> (c) if I substitute 10 for n and do "10 + round(sqrt 10)" I get the
> expected answer 13
>
> any help most welcome.
>
> cheers,
>
> Ivan
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20090327/b9b9f8aa/attachment.htm


More information about the Beginners mailing list