在haskell中每2个换行字符分割字符串



我的输入看起来像

abc
a
b
c
abc
abc
abc
abc

我需要一个函数把它分成像

这样的东西
[ "abc"
, "anbnc"
, "abcnabcnabcnabc"]

我试过使用正则表达式,但是

  1. 我不能导入Text.Regex本身
  2. Module Text.Regex.Base不输出splitStr

在这种情况下使用正则表达式通常是一个坏主意,因为它的可读性不如纯代码和简洁的代码,可以在这里使用。

例如使用foldr,我们应该在字符串列表中添加新字符串的唯一情况是最后看到的元素和当前元素是newline的情况:

split :: FilePath -> IO [String]
split path = do
text <- readFile path
return $ foldr build [[]] (init text)
where 
build c (s:ls) | s == [] || head s /= 'n' || c /= 'n' = (c:s)       : ls  
| otherwise                              = [] : tail s : ls

当给定具有上述内容的文件时,此代码将产生上述结果。

最新更新