Created
          February 12, 2013 16:52 
        
      - 
      
- 
        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
  
        
  
    
      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
    
  
  
    
  | 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 | 
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) KiloGramAny 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
  
            
We don't need Eq on MetricUnit and ImperialUnit, since we can implement the functions in another, more Haskell way:
Isn't this way also easier to read?