2011-03-16 98 views
1

我試圖將文本格式化爲矩形的形狀;目前我已經能夠正確地得到它,但最後一行並沒有儘可能延長。Haskell:遞歸問題

我試圖計算最佳的字段寬度,以最大限度地減少或完全刪除它。

我完全卡住了。下面的代碼顯示了相關的功能。目前它陷入了無限循環。 我哪裏錯了?

在附註中,調試Haskell代碼的最佳方法是什麼? (是的,我對此很新穎。)

optimalFieldWidth應該比較行長度,直到頂行的長度等於底行的長度,然後返回導致它的字段寬度真正。

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 

所有回覆讚賞。謝謝。

回答

1

我想我應該把實際的解決方案在這裏情況下,任何其他瘋子想做到這一點。 請注意,它是由白癡寫的,所以它可能不是最優雅的解決方案。

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 
0

看來,條件length (last input) == length (head input)一次假從未在後續調用area爲真,從而使這一功能始終以otherwise分支,並保持自稱無限期使用的xs相同的值,從而input

的這個可能的原因是您使用lines功能,其將使用新行字符的字符串,在不依賴於lineLength,不符合在rect功能的分線的方式。

+0

對不起。我剛剛意識到這個名字是多麼的錯誤。它應該比較行長度,直到頂行的長度等於底行的長度,然後返回導致其爲真的字段寬度。 – ratbum 2011-03-16 20:27:19

+0

@ratbum我已更新我的答案,以解釋您添加的信息。 – Rotsor 2011-03-16 20:51:53