optimumFieldWidth应该比较行的长度，直到顶行的长度等于底行的长度，然后返回使之成为真的字段宽度。

``````module Main where

import System
import Data.List

main = do
(f:_) <- getArgs
xs <- getContents
putStr (show (bestFieldWidth maxLineLength xs))

bestFieldWidth :: Int -> String -> Int
bestFiledWidth _ [] = 0
bestFieldWidth lineLength xs
| length (last input) == length (head input) = lineLength
| otherwise = bestFieldWidth (length (head (rect (lineLength-1) xs))) xs
where input = lines xs

rect :: Int -> String -> [String]
rect _ [] = []
rect lineLength xs
| length input <= len = [input]
| otherwise           = take len input : rect len (drop len input)
where input = trim xs
len   = bestFieldWidth lineLength xs

maxLineLength :: Int
maxLineLength = 40
``````

3 个回复

``````maxFieldWidth :: Int
maxFieldWidth = 30

rect :: String -> String
rect xs  = (unlines (chunk (bestFieldWidth (maxFieldWidth) (lines input)) input))
where input = itemsReplace '\n' ' ' xs

--Should be called with the point maximum desired width as n
bestFieldWidth :: Int -> [String] -> Int
bestFieldWidth _ [] = error "bestFieldWidth: Empty List"
bestFieldWidth n xs
| n == 6 = 6
| 1 == (length (last input)) = n
| otherwise = (bestFieldWidth (n-1) xs)
where input = chunk n (unlines xs)

chunk :: Int -> [a] -> [[a]]
chunk n [] = []
chunk n xs = ys : chunk n zs
where (ys,zs) = splitAt n xs

itemsReplace :: Eq a => a -> a -> [a] -> [a]
itemsReplace _ _ [] = []
itemsReplace c r (x:xs)
| c == x    = r:itemsReplace c r xs
| otherwise = x:itemsReplace c r xs
``````

2009-10-06 09:39:32 1 669   parsing

2014-08-07 03:50:26 1 226   list/ maze