0

I am new to Haskell and learning about data types. I am attempting to do a simple problem, but I cant seem to grasp the bigger picture. I have a data type of LengthUnit which resembles inches, feet, and yards. I want to make a function that takes a list of lists of LengthUnits and converts them to inches and sums all elements.

I created a helper function convert, which converts the LengthUnit to inches. I also have addLengths which accepts two LengthUnits and adds them up. I cant seem to get the output I am looking for. 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 x y = INCH ((convert x) + (convert y))


-- addAllLengths
--addAllLengths :: Foldable t => [t LengthUnit] -> LengthUnit
addAllLengths list = let nList = map convert list
                     in foldr addLengths 0 nList

From the above I get an error: Couldn't match type 'Int' with 'LengthUnit'. Any help would be appreciated.

I'm looking to get something like this:

addAllLengths [[FOOT 2], [FOOT 2, INCH 2],[]]
INCH 50

1 Answer 1

3

Try this:

addAllLengths list = foldr addLengths (INCH 0) (concat list)

concat turns [[FOOT 2], [FOOT 2, INCH 2],[]] into [FOOT 2, FOOT 2, INCH 2], and then foldr addLengths (INCH 0) turns that into INCH 50.

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

1 Comment

Thank, I didn't know about concat. That would come in handy

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.