If I have a recursive function that does comparisons on every element on a list; what is the best way to have it do an extra step at then end as if the list had an extra 0 on the end, without actually appending 0 to the list in the first place.
rect xs = maximum $ go 0 [] (xs ++ [0]) where
go i s [] = []
go i ((_, tH):r@((t,_):_)) (h:hs) | h < tH = tH * (i - t - 1) : go i r (h:hs)
go i s (h:hs) = go (i + 1) ((i,h):s) hs
I am think that there must be a better way than doing the xs ++ [0] but I can't come up with it.
Note: The function is to find the largest rectangle in a histogram
go'that mimicsgo, so that you can callgo i s [] = go' i s [0], but I think that would get more complicated than what you have now. What you have now looks fine.++is lazy, so each time you try to get an element from the list,h:hsjust gets matched againstx : xs ++ [0]instead ofx:xs.++is only bad if you try to build up a list by appending to it one item at a time; here, you are only appending one single item.h:hsgets matched againstxs ++ [0]; to evaluatexs ++ [0], they:yspattern in the implementation of++gets matched againstxs. This is one extra match compared to not having called++-- in other words, over the course of touching the whole list, you have done one extra walk.