1

I've been trying to learn haskell for a couple days but I can't see to figure out how to create an answer/output that is a float, to a double

module SpaceAge ( Planet(..), ageOn) where
-- calculate seconds to an age on different planets
data Planet = Earth
            | Jupiter
            | Mars
            | Mercury
            | Neptune
            | Saturn
            | Uranus
            | Venus

-- one year has 31557600 seconds
orbitalPeriodInSeconds :: Planet -> Float
orbitalPeriodInSeconds planet = 31557600 * multiplier where
    multiplier = case planet of
        Earth   -> 1.0
        Jupiter -> 11.862615
        Mars    -> 1.8808158
        Mercury -> 0.2408467
        Neptune -> 164.79132
        Saturn  -> 29.447498
        Uranus  -> 84.016846
        Venus   -> 0.61519726

-- user input example: ageOn Venus 9303000
ageOn :: Planet -> Float -> Float
ageOn planet seconds = seconds / orbitalPeriodInSeconds planet

The answer/output will be a float but I need to get a double. Example

*SpaceAge> ageOn Mercury 2134835688
280.87936

But I need 280.88
Offcourse the compiler will raise errors if I change Float to Double because it expect a Float.

Romano
  • 117
  • 1
  • 2
  • 12
  • 5
    I think there's a misunderstanding here: `280.87936` and `280.88` could both be `Float` *or* `Doubles`. Do you actually need a `Double`, or do you want to round your answer to two decimal points? – Tikhon Jelvis Dec 05 '16 at 23:05
  • 1
    `orbitalPeriodInSeconds` doesn't need to return a `Float`; it can return a polymorphic value whose type is an instance of the `Fractional` type class. (`orbitalPeriodInSeconds :: Fractional a => Planet -> a`). The same goes for `ageOn :: Fractional a => Planet -> a -> a`. – chepner Dec 05 '16 at 23:32
  • might be a duplicate of http://stackoverflow.com/questions/1559590/haskell-force-floats-to-have-two-decimals – Jean-Baptiste Potonnier Dec 05 '16 at 23:41
  • 4
    You say "of course the compiler will raise errors if I change Float to Double"; I challenge you to test this hypothesis. When *I* change all the instances of `Float` to `Double`, the compiler doesn't complain at all. "I get `280.87936` but I need `280.88`" is a mostly unrelated issue. – Daniel Wagner Dec 06 '16 at 00:07
  • 4
    A good rule of thumb is "Never use `Float`." There are some special exceptions when dealing with certain protocols, special hardware, numerical recipes, or when really trying to pack things up tightly, but when you think of `Float` you should almost always use `Double` instead. – dfeuer Dec 06 '16 at 02:58

1 Answers1

3

If the need is to display the result you can use showFFloat from Numeric

showFFloat (Just 2) 280.87936 ""