繁体   English   中英

Haskell:递归问题

[英]Haskell: problem with recursion

我正在尝试将文本格式设置为矩形。 目前,我已经能够使它正确地左对齐,但是最后一行没有尽可能延伸。

我正在尝试计算最佳字段宽度,以最小化或完全消除此宽度。

我完全被困住了。 下面的代码显示了相关功能。 此刻,它陷入了无限循环。 我要去哪里错了?

附带说明一下,调试Haskell代码的最佳方法是什么? (是的,我对此很陌生。)

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

感谢所有答复。 谢谢。

我以为我会把实际的解决方案放在这里,以防任何其他消息者希望这样做。 请记住,它是由白痴编写的,因此它可能不是最优雅的解决方案。

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

似乎条件length (last input) == length (head input)一旦为false,则在后续对area调用中永远不会变为true,因此使该函数始终采用otherwise分支,并以相同的xs值无限期地调用自身,因此input

造成这种情况的可能原因是,您使用了lines函数,该函数使用换行符分隔字符串,而这种方式不依赖于lineLength且与rect函数中的换行不一致。

为了回答您的旁注,以下是调试Haskell的出色指南: http : //cgi.cse.unsw.edu.au/~dons/blog/2007/11/14

还有Debug.Trace,它允许您插入打印语句。 当然,它只能在调试时使用,因为它会使您的函数产生副作用。

http://hackage.haskell.org/packages/archive/base/latest/doc/html/Debug-Trace.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM