我正在尝试使用一些递归来创建字符串列表。
基本上我想将字符串的一部分提取到某个点。从中创建一个列表,然后通过递归处理字符串的其余部分。
type DocName = FilePath
type Line = (Int,String)
type Document = [Line]
splitLines :: String -> Document
splitLines [] = []
splitLines str | length str == 0 = []
| otherwise = zip [0..(length listStr)] listStr
where
listStr = [getLine] ++ splitLines getRest
getLine = (takeWhile (/='\n') str)
getRest = (dropWhile (=='\n') (dropWhile (/='\n') str))
这就是我得到的。但它只是将字符串重新组合在一起,因为它们本身就是字符列表。但我想创建一个字符串列表。
["test","123"] 如果输入是 "test\n123\n"
谢谢
最佳答案
如果您尝试编译您的代码,您会在行中收到一条错误消息告诉您
listStr = [getLine] ++ splitLines getRest
splitLines getRest
的类型为 Document
,但它的类型应该为 [String]
。这很容易理解,因为 [getLine]
是一个字符串列表(一个字符串列表),所以它只能与另一个字符串列表连接,而不是一个 int-字符串元组。
因此,为了解决这个问题,我们可以使用 map 将 Document 中的每个 int-string-tuple 仅替换为字符串以获取字符串列表,即:
listStr = [getLine] ++ map snd (splitLines getRest)
将行更改为上面的代码后,您的代码将编译并运行得很好。
But it just concats the strings back together since they are list of characters themselves.
我不确定你为什么这么想。
您的代码未编译的原因是因为 splitLines
的类型,正如我上面所解释的。修复该错误后,代码将完全按照您的意愿运行,返回整数字符串元组列表。任何时候都不会连接字符串。
关于list - Haskell - 连接字符串列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3824393/