Skip to content

Instantly share code, notes, and snippets.

@BinRoot
Created February 12, 2013 16:52
Show Gist options
  • Save BinRoot/4771288 to your computer and use it in GitHub Desktop.
Save BinRoot/4771288 to your computer and use it in GitHub Desktop.
Haskell code used in Lecture 5 from http://shuklan.com/haskell/lec05.html
module MyData
(MetricUnit(..),
ImperialUnit(..),
Measurement(..),
convert)
where
data MetricUnit = Meter
| Liter
| KiloGram
deriving (Show, Eq)
data ImperialUnit = Yard
| Gallon
| Pound
deriving (Show, Eq)
data Measurement = MetricMeasurement Double MetricUnit
| ImperialMeasurement Double ImperialUnit
deriving (Show)
symbol :: MetricUnit -> String
symbol x
| x == Meter = "m"
| x == Liter = "L"
| x == KiloGram = "kg"
convert (MetricMeasurement x u)
| u==Meter = ImperialMeasurement (1.0936*x) Yard
| u==Liter = ImperialMeasurement (0.2642*x) Gallon
| u==KiloGram = ImperialMeasurement (2.2046*x) Pound
convert (ImperialMeasurement x u)
| u==Yard = MetricMeasurement (0.9144*x) Meter
| u==Gallon = MetricMeasurement (3.7854*x) Liter
| u==Pound = MetricMeasurement (0.4536*x) KiloGram
@md2perpe
Copy link

We don't need Eq on MetricUnit and ImperialUnit, since we can implement the functions in another, more Haskell way:

symbol :: MetricUnit -> String
symbol Meter = "m"
symbol Liter = "L"
symbol KiloGram = "kg"



convert :: Measurement -> Measurement

convert (MetricMeasurement x Meter) = ImperialMeasurement (1.0936*x) Yard
convert (MetricMeasurement x Liter) = ImperialMeasurement (0.2642*x) Gallon
convert (MetricMeasurement x KiloGram) = ImperialMeasurement (2.2046*x) Pound

convert (ImperialMeasurement x Yard) = MetricMeasurement (0.9144*x) Meter
convert (ImperialMeasurement x Gallon) = MetricMeasurement (3.7854*x) Liter
convert (ImperialMeasurement x Pound) = MetricMeasurement (0.4536*x) KiloGram

Isn't this way also easier to read?

@btv
Copy link

btv commented Feb 15, 2013

Maybe I'm wrong with this line of thinking (which you can maybe address in next week's slides), but I generally consider guards to be equivalent to if-else statements. Also, I was taught that it was more efficient to use a switch statement instead in those situations, because of that I changed my convert to look like so:

convert (ImperialMeasurement x u) = case u of                                
    Yard   -> MetricMeasurement (0.9144 * x) Meter                            
    Gallon -> MetricMeasurement (3.7854 * x) Liter                            
    Pound  -> MetricMeasurement (0.4536 * x) KiloGram

Any direction on this line of thinking would be appreciated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment