[Haskell-beginners] A better way?

Daniel Fischer daniel.is.fischer at web.de
Sat Feb 21 17:58:41 EST 2009

Am Samstag, 21. Februar 2009 23:29 schrieb Thomas Davie:
> How about this:
> maxTableColumnWidths :: [[String]] -> [Int]
> maxTableColumnWidths = map (maximum . map length)

That's not what he needs, 

maxTableColumnWidths = map (maximum . map length) . transpose

would be it. But I'm afraid that wouldn't solve his memory problems.

Regarding the memory problems: String is rather a memory hog anyway.
Keith, have you considered using ByteStrings? That might solve your memory 
problems with a straightforward algorithm.

Also, if the rows can contain many columns, it is wasteful to calculate the 
length of prevMaxValues for every row. You could either have that as a 
parameter, or use a custom zipWith:

zipWithD :: (a -> a -> a) -> [a] -> [a] -> [a]
zipWithD f (x:xt) (y:yt) = f x y:zipWithD f xt yt
zipWithD _ [] ys = ys
zipWithD _ xs [] = xs

Then maxRowFieldWidths would become

maxRowFieldWidths row prev = zipWithD max (map length row) prev

or, pointfree:

maxRowFieldWidths = zipWithD max . map length

seqList can also be written as

seqList = foldr seq False

That would make

maxTableColumnWidths = foldr ((seqList .) . zipWithD max) []

I'm not sure if that is strict enough, though.

Also, you might try

maxTCWs = foldr seq [] . foldr (zipWithD max) []

, but I expect that to be a bad memory citizen.

> Bob


More information about the Beginners mailing list