[Haskell-cafe] Instantiation problem

Patrick Browne patrick.browne at dit.ie
Fri Jan 28 12:42:48 CET 2011

Below is some code that is produces information about the *types* used
for measuring (e.g. metres).  The following evaluation returns 1.00
which the convert factor for metres.

convertFactorToBaseUnit (unit (LengthInMetres  7))
The next evaluation returns the type, Metre, of data being measured
unit (LengthInMetres  7)

Using the particular definitions below is it possible to make an
instance of MetricDescription for centimetres? I have an error on the
defintion of the unit function in the definition of the
MetricDescription  instance.
As far as possible I would like to retain the data types and class


class (Unit unit) => MetricDescription description unit | description ->
unit where
 unit :: description -> unit
 valueInUnit :: description -> Double
 valueInBaseUnit :: description -> Double
 valueInBaseUnit d = (convertFactorToBaseUnit(unit d)) * (valueInUnit d)

data Metre = Metre  deriving Show
data Centimetre = Centimetre deriving Show

-- Each member of the Unit class has one operator convertFactorToBaseUnit
-- that takes a measurement unit (say metre) and returns a conversion
factor for that unit of measurement
class  Unit unit where
  convertFactorToBaseUnit :: unit -> Double

-- An instance for metres, where the convert factor is 1.0
instance Unit Metre where
 convertFactorToBaseUnit Metre  = 1.0

-- An instance for metres, where the convert factor is 0.1
instance Unit Centimetre where
  convertFactorToBaseUnit Centimetre  = 0.1

data LengthInMetres = LengthInMetres Double  deriving Show
data LengthInCentimetres = LengthInCentimetres Double  deriving Show

-- This seems fine
instance MetricDescription LengthInMetres Metre where
 valueInUnit (LengthInMetres d) = d
 unit l = Metre

-- This is the instance that I cannot get to work
-- The unit 2 function seems to be the problem.
-- instance MetricDescription LengthInCentimetres Centimetre where
--  valueInUnit (LengthInCentimetres d) = d
--  unit 2 = Centimetre

This message has been scanned for content and viruses by the DIT Information Services E-Mail Scanning Service, and is believed to be clean. http://www.dit.ie

More information about the Haskell-Cafe mailing list