Johnny Cash
Johnny Cash

Reputation: 7

Returning Doubles in haskell

Now what I want to do is to write another function, triangle_areas (note the use of plural here), that takes a list of Doubles, treats each consecutive group of three Doubles as the lengths of the three sides of a triangle, uses triangle_area to calculate its area; and after processing all Doubles in the list, returns all calculated areas as a list of Doubles.

Here is my code so far.

triangle_area :: Double -> Double -> Double -> Double
triangle_area a b c = sqrt (s * (s - a) * (s - b) * (s - c))
    where s = (a + b + c) / 2.0

triangle_areas :: [Double] -> [Double]
triangle_areas xs = []

Upvotes: 1

Views: 654

Answers (1)

chepner
chepner

Reputation: 531055

Use pattern matching to get the first three elements of the input, then recurse. It's simplest if you assume triangle_areas is always called with a list whose length is a multiple of 3.

triangle_areas :: [Double] -> [Double]
triangle_areas [] = []
triangle_areas (a:b:c:xs) = triangle_area a b c : triangle_areas xs

For lists with an extra element or two, there are many options. One is to simply ignore them.

-- Case 3
triangle_areas _ = []

Another is to simple return an error

-- Case 3
triangle_areas _ = error "Incomplete final set"

Yet another is to return an Either value

triangle_areas :: [Double] -> Either String [Double]
triangle_areas [] = Right []
triangle_areas (a:b:c:xs) = Right $ triangle_area a b c : triangle_areas xs
triangle_areas _ = Left "Incomplete final set"

And there are others.

Upvotes: 4

Related Questions