Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

[Haskell-beginners] Retrieving the decimal portion of a Double

3 views
Skip to first unread message

Dominic Sim

unread,
Nov 23, 2009, 9:31:19 AM11/23/09
to begi...@haskell.org
��� Hi all,

��� I am trying to retrieve the decimal portion of a Double. My code is:

��� getDecimal x = x - floor(x)

��� I would expect the following:

��� Main> getDecimal 1.23
��� 0.23 :: [Double]

��� but instead, I get:

��� Main> getDecimal 1.23
��� ERROR - Unresolved overloading
��� *** Type������ : (RealFrac a, Integral a) => a
��� *** Expression : getDecimal 1.23

��� I have tried adding "getDecimal :: Double -> Double" but it only causes the following message to appear:

��� ERROR file:C:\Documents and Settings\User\file.hs:60 - Instance of Integral Double required for definition of getDecimal

��� How should I define my function so that it'll work? Thanks!

��� Regards,
��� Dom

Shawn Willden

unread,
Nov 23, 2009, 10:45:20 AM11/23/09
to begi...@haskell.org
On Monday 23 November 2009 07:31:05 am Dominic Sim wrote:
>     I am trying to retrieve the decimal portion of a Double. My code is:
>
>     getDecimal x = x - floor(x)

The problem is that x is a double (or some other kind of floating point or
fraction), and "floor x" is an integer, and you can't subtract an integer
from a double. To convert "floor x" to a double (or to any other relevant
type), use "fromIntegral", like:

getDecimal x = x - fromIntegral(floor x)

However, what I'd really suggest is that you use:

getDecimal x = snd (properFraction x)

or, in pointfree style:

getDecimal = snd . properFraction

Also, the type signature for getDecimal should be:

getDecimal :: RealFrac a => a -> a

That will allow it to be used with any Real or Fractional type.

Shawn.

_______________________________________________
Beginners mailing list
Begi...@haskell.org
http://www.haskell.org/mailman/listinfo/beginners

0 new messages