I'm trying to understand recursion with the functions of Haskell, but I have some problems with this function, in particular with foldr function:
I have declared a data Shape in this manner:
type P = (Int, Int) -- point
type V = (Int, Int) -- vector
data Shape =
Line P P -- line characterized by two vertices
| Triangle P P P -- characterized by three triangle vertices
deriving (Eq, Show)
Now, given a list of forms, I have to extract the shape that has greater area
maxArea :: [Shape] -> Shape
maxArea list = maxArea_hlp list 0
maxArea_hlp :: [Shape] -> Int -> Shape
maxArea_hlp list areaMax = foldr (\shape currmax -> if ((area shape) > (area currmax)) then shape else (shape:list)) 0 list
area :: Shape -> Int
area (Line _ _) = 0
area (Triangle p1 p2 p3) = 0
--TODO
The error is:
Couldn't match expected type Shape with actual type [Shape]
In the expression: (shape : list)
The error lies in the "else" branch of the lambda function, but I do not understand how to solve it.
Can you help me please?
Thanks to all
currmaxsupposed to be? According to the type signature offoldr((a -> b -> b) -> b -> [a] -> b), it should be numeric (the same as0), but you also callareaon it, which suggests that it should beShape. There lies your mistake. Usingfoldrfor this is awkward. Why not usemaximumBy?Shapein one branch of the if and a[Shape]in the other branch, which doesn't type-check. Is there a particular reason you're usingfoldrhere instead ofData.List.maximumBy? You aren't even usingareaMax, so instead it could just bemaximumBy (comparing area), withData.Ord.comparing.maximumBybecause I have to use only high-order functions; thanks a lot, I will try to fix it now.maximumByis a higher-order function because it takes a function (how to compare the items) as an input.