Last active
October 3, 2020 08:17
-
-
Save craftybones/b7b8586bc5df2bd91e9e73db48284351 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Unit a where | |
standard :: a | |
class RatioUnit a where | |
standardFactor :: a -> Float | |
toStandard :: (RatioUnit a) => a -> Float -> Float | |
toStandard a x = (standardFactor a) * x | |
data Measure b = Measure Float b deriving (Show) | |
data LengthUnit = Meter | Kilometer deriving (Show,Eq) | |
data AreaUnit = SqMeter | SqKilometer deriving (Show,Eq) | |
data TemperatureUnit = Celsius | Fahrenheit | Kelvin deriving (Show,Eq) | |
instance Unit LengthUnit where | |
standard = Meter :: LengthUnit | |
instance Unit AreaUnit where | |
standard = SqMeter :: AreaUnit | |
instance Unit TemperatureUnit where | |
standard = Kelvin :: TemperatureUnit | |
instance (RatioUnit a) => Eq (Measure a) where | |
(Measure x u1) == (Measure y u2) = (toStandard u1 x) == (toStandard u2 y) | |
add :: (RatioUnit a, Unit a) => Measure a -> Measure a -> Measure a | |
add (Measure q1 u1) (Measure q2 u2) = | |
let standardQ1 = toStandard u1 q1 | |
standardQ2 = toStandard u2 q2 | |
in Measure (standardQ1 + standardQ2) (standard) | |
instance RatioUnit LengthUnit where | |
standardFactor Meter = 1.0 | |
standardFactor Kilometer = 1000.0 | |
instance RatioUnit AreaUnit where | |
standardFactor SqMeter = 1.0 | |
standardFactor SqKilometer = 1000000.0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Unit a where | |
baseFactor :: a -> Float | |
coefficient :: a -> a -> Float | |
coefficient a b = (baseFactor a)/(baseFactor b) | |
data Measure b = Measure Float b deriving (Show,Eq) | |
convert :: (Unit b) => Measure b -> b -> Measure b | |
convert (Measure qty unit) newUnit = Measure (qty*(coefficient unit newUnit)) newUnit | |
data LengthUnit = Meter | Kilometer deriving (Show,Eq) | |
data AreaUnit = SqMeter | SqKilometer deriving (Show,Eq) | |
instance Unit LengthUnit where | |
baseFactor Meter = 1 | |
baseFactor Kilometer = 1000 | |
instance Unit AreaUnit where | |
baseFactor SqMeter = 1 | |
baseFactor SqKilometer = 1000000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment