简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM