Kieran Atkins
Kieran Atkins

Reputation: 65

Creating a program that accumulates parts of a list - Haskell

I'm working on a program the will takes a list of triples and depending on one of those being true, I want to find the sum of one of the other parts of the triple.

totalWeightOfFirstClass :: [Parcel] -> Weight
totalWeightOfFirstClass [] = go
totalWeightOfFirstClass ((weight, postcode, firstclass):xs) =
  if firstclass == True then
    go weight
    totalWeightOfFirstClass xs
  else
    totalWeightOfFirstClass xs
where
  go :: Int -> Int
  go _ = 0
  go x =

So the program should add up all the weight values in the list and display it at the end only if the that triple was first class. So far I have a helper statement that I want to accumulate all the values and to eventually display at the end.

Any help or advice would be much appreciated.

Regards, Kieran.

Upvotes: 0

Views: 95

Answers (2)

Jason Hu
Jason Hu

Reputation: 6333

That's too much work in your code. Try to consider using general combinator to express your code, instead of writing primitive recursion like this.

totalWeightOfFirstClass = sum . (fmap (\(weight, _, _) -> weight)) . filter (\(_, _, firstc) -> firstc)

It sum all the weights after applying the filter. As you can see, the code is very clean to read.

Upvotes: 2

Zpalmtree
Zpalmtree

Reputation: 1369

If I'm understanding you correctly, you want the sum of the weights where the parcel is sent first class, this should do the trick:

totalWeightOfFirstClass :: [Parcel] -> Weight
totalWeightOfFirstClass [] = 0
totalWeightOfFirstClass ((weight, postcode, firstclass):xs)
    | firstclass = weight + totalWeightOfFirstClass xs
    | otherwise = totalWeightOfFirstClass xs

Upvotes: 1

Related Questions