Alex
Alex

Reputation: 185

Haskell - data type functions

I'm learning Haskell and started looking over data types. I tried doing a simple example with converting Yard and feet to inches with a data type defined as LengthUnit. I want to add two LengthUnit vars so I created a helper function called convert that would take in a LengthUnit and convert it to inches.

I tried to do the following but I keep getting an error 'Couldnt match expected type LengthUnit with type Int.

Here is what I have:

data LengthUnit =  INCH  Int | FOOT  Int | YARD  Int
                   deriving (Show, Read, Eq)

convert :: LengthUnit -> Int    
convert (INCH x) = x 
convert (FOOT x) = x * 12
convert (YARD x) = x * 36

-- addLengths 
addLengths :: LengthUnit -> LengthUnit -> LengthUnit
addLengths (INCH x) (INCH y) = convert(x) + convert(y)
-- I tried this as well and still receive same error
addLengths (INCH x) (INCH y) = x + y
addLengths (INCH x) (FOOT y) = convert(x) + convert(y)
.
.
.

I cant seem to find the equivalence of :

addLengths (LengthUnit x) (LengthUnit y) = convert(x) + convert(y)

Any help is appreciated, thanks!

Upvotes: 1

Views: 211

Answers (1)

Dan D.
Dan D.

Reputation: 74685

You mean something like:

addLengths x y = INCH ((convert x) + (convert y))

There might be more parentheses than required.

The use of the INCH constructor is not a type cast.

Upvotes: 3

Related Questions