[Haskell-beginners] how to print a floating-point number?
daniel.is.fischer at web.de
Thu Jan 8 13:28:59 EST 2009
Am Donnerstag, 8. Januar 2009 17:45 schrieb Sergei Winitzki:
> Subject: how to print a floating-point number?
> I am very new to Haskell. I am trying to benchmark the CPU time needed
> for a computation, and I can't figure out how to print a
> floating-point number.
> My code is as follows, and I expected it to work:
> import System.CPUTime
> main = do
> let result = some_computation
> print result
> time <- getCPUTime -- this is an Integer that needs
> to be divided by 1e12 to get time in seconds
> print (time / 1.0e12) -- I want this to print a
> floating-point number
You have to convert the Integer to a floating point number first, use
for that. Haskell does not do automatic conversion between numeric types.
> But this does not compile.
> Error message: No instance for (Fractional Integer)
> arising from use of `/' at fact1.hs:18:15-28
> Possible fix: add an instance declaration for (Fractional Integer)
> In the first argument of `print', namely `(time1 / 1.0e12)'
> I thought this should work because e.g. 12 / 7 evaluates to
> 1.7142857142857142 in ghci.
That is because numeric *literals* are polymorphic, as they are parsed as e.g.
"fromInteger 12" if it's an integer literal or "fromRational 3.24" if it's a
> I understand this is some problem with types, but surely it is fixed
> not by adding any instance declarations but perhaps by using some
> Prelude or Numeric function. But which one?
> I tried everything I could find in the documentation: showFloat,
> adding ::Float everywhere, adding fromIntegral, etc.etc. - nothing
> works. All the books and the tutorials I looked at seem to discuss at
> length such nice things as Fibonacci numbers and recursive factorial
> functions rather than a practical problem like this.
When you are looking for a function, it's a good idea to ask hoogle
(http://haskell.org/hoogle/) for a function of appropriate type. Asking for a
function Integer -> Double, the abovementioned are results 1 and 3.
> help will be much appreciated!
More information about the Beginners