[英]Stopping condition on a recursive function - Haskell
因此,我具有此功能,旨在使文本在左侧对齐而不剪切单词(仅保留空白)。 但是,我的问题是我找不到该函数的停止条件,并且它无限进行。
f n "" = "" --weak condition
f n s = if n >= ((maximum . map length . words) s) then if (s !! n == ' ' || s !! n == '\t' || s !! n == '\n')
then take n s ++ "\n" ++ (f n ( drop n s)) else f (n-1) s
else error "Try bigger width!"
好吧,基本上,如果n小于最长的单词,则提示错误,否则它会在空白中“剪切”字符串,直到到达非空白字符为止,然后对n-1
递归调用。 我也使用putStr
来避免输出中的“ \\ n”。
但是,正如我已经说过的,停止条件太弱或根本不存在。 如果代码中还有其他流程或可能的优化措施(例如,较少的ifs),请告知。
您的代码无法处理行短于最大长度的情况。
这在某种程度上被另一个错误所掩盖:将n
递减直到找到空白,然后调用f
递归传递n
递减值,从而有效地将所有后续行限制为当前行的长度。
(此外,您可能希望从s
删除n + 1
字符,以便在输出中不包含原始空格。)
您可以使用模式来避免ifs:
f n "" = "" -- weak condition
f n s
| n >= (maximum . map length . words) s =
if s !! n == ' ' || s !! n == '\t' || s !! n == '\n'
then take n s ++ "\n" ++ f n (drop n s)
else f (n - 1) s
| otherwise = error "Try bigger width!"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.