1

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!

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@Alex That isn't a type cast. It is using the INCH constructor to make a LengthUnit value from an Int value. To give a quick example of one difference from type casting, constructors can take multiple arguments (this is just one slight, quick motivation for the difference. They are really fundamentally different things overall). Haskell doesn't really have type casting in the way a language like C does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.