我想使用Haskell格式化文本,并给出字符串和行长。但是,无缘无故地在“块”函数中出现相同的未知错误!这是代码:
module Format where
data Format = Flushleft | Justify | Flushright
-- Help-function for chunks
oneChunk :: [String] -> [[String]]
oneChunk [] = [[]]
oneChunk (s:ls) = [words s] ++ oneChunk ls
chunks :: Int-> [String]-> [[String]]
chunks i s = chunk' i (oneChunk s) where
chunk' i [[]] = [[]]
chunk' i (fi:se:ls)
| (length fi) + (length se) < i = [fi ++ se]
++ chunk' i (se:ls)
| otherwise = [fi] ++ [se] ++ chunk' i (se:ls)
这是错误消息:
Format.hs:13:14: error:
parse error (possibly incorrect indentation or mismatched brackets)
|
13 | | (length fi) + (length se) < i = [fi ++ se] ++
chunk' i (se:ls)
|
答案 0 :(得分:4)
如错误消息中所述,缩进不正确。您需要相对于函数声明缩进模式保护符(请参见Control structures)。
所以您的代码应如下所示:
chunks :: Int-> [String]-> [[String]]
chunks i s = chunk' i (oneChunk s) where
chunk' i [[]] = [[]]
chunk' i (fi:se:ls)
| (length fi) + (length se) < i = [fi ++ se]
++ chunk' i (se:ls)
| otherwise = [fi] ++ [se] ++ chunk' i (se:ls)
我不明白您要解决什么问题,但似乎可以稍微简化一下代码。
oneChunk
将words
应用于其参数的每个元素,并在末尾添加[]
。可以这样表示(有关更多信息,请在map
s和pointfree style上阅读一点)。
oneChunk = (++[]) . map words
chunk'
使用i
中的变量chunks
,因此您可以删除它。另外,不需要一些括号,您可以将[x] ++ y
替换为x:y
):
chunks :: Int-> [String]-> [[String]]
chunks i = chunk' . map words where
chunk' [] = []
chunk' (fi:se:ls)
| length fi + length se < i = (fi ++ se) : chunk' (se:ls)
| otherwise = fi : se : chunk' (se:ls)