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:
(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
CodePudding user response:
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.