Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Haskell data type in list

I have a data type which looks like this:

data Vector3 = V Int Int Int deriving (Eq, Show)

And I have to write this function:

vectorListSum :: [Vector3] -> Vector3

Which should sum the parameters on the same index, so:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(V1 a1 b1 c1) + (V2 a2 b2 c2) => (V3 a1+a2 b1+b2 c1+c2)

And so on, depending on how many elements the list have

I tried something like this:

vectorListSum :: [Vector3] -> Vector3
vectorListSum [] = V 0 0 0
vectorListSum ((V a b c):xs) = ...

But I couldn’t go any further

>Solution :

You can work with foldr or foldl:

vectorListSum :: [Vector3] -> Vector3
vectorListSum = foldr f (V 0 0 0)
    where f (V …) (V …) = …

where f takes as input a vector and the "fold" of the rest of the list, and thus determines the fold of the entire list. I leave filling in the parts as an exercise.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading