I made the following class to convert between different temperature types:
data Temp = Kelvin Float | Celsius Float |Fahrenheit Float deriving Show
conversionKelvin:: Temp -> Temp
conversionKelvin (Celsius x) = Kelvin (x + 273.15)
conversionKelvin (Fahrenheit x) = Kelvin((x - 32) * 5/9 + 273.15)
conversionKelvin (Kelvin x) = Kelvin x
conversionCelsius:: Temp -> Temp
conversionCelsius (Kelvin x) = Celsius (x - 273.15)
conversionCelsius (Fahrenheit x) = Celsius((x - 32) * 5/9)
conversionCelsius (Celsius x) = Celsius x
conversionFahrenheit:: Temp -> Temp
conversionFahrenheit (Celsius x) = Fahrenheit (x * 9/5 + 32)
conversionFahrenheit (Kelvin x) = Fahrenheit((x - 273.15)*9/5 + 32)
conversionFahrenheit (Fahrenheit x) = Fahrenheit x
So far all's good, however I want to implement the instance Eq and Ord. I thought about converting each type to celsius and then see which is bigger, but I can't manage to get past the compiler. Any help?
Edit: Here's my attempt at instancing Eq:
instance Eq Temp where
a == b = conversionCelsius(a) == conversionCelsius(b)
It compiles but it makes haskell enter some kind of loop (doesn't print the output)
instance Eq? Beware that floating-point calculations often have rounding errors, so two values can be equal "by accident" if they are close to each other and vice versa. - Willem Van OnsemKelvintoKelvin, etc. - Willem Van OnsemFloatwith an arbitrary-precision exactRational(fromData.Ratio), then usefromRationalto convert to fixed precision at the end. Otherwise, for example, converting a temperature from Celsius to Fahrenheit and back will not necessarily produce values that will compare equal with(==):let { x = 1 :: Rational; } in (x, ((x * 9/5 + 32.0) - 32.0) * 5/9)produces exactly equal values(1 % 1, 1 % 1), but usingFloat/Doubleinstead produces unequal values(1.0,0.9999996)/(1.0,0.9999999999999984). - Jon PurdyEqandOrdare trivial and derivable. - chepner