【问题标题】:Haskell split lines into list including empty linesHaskell 将行拆分为列表,包括空行
【发布时间】:2010-09-29 18:50:39
【问题描述】:

有这个

type DocName = FilePath
type Line = (Int,String)
type Document = [Line]

splitLines :: String -> Document
splitLines [] = []
splitLines str = zip [0..(length listStr)] listStr
                                    where 
                                        listStr = [getLine] ++ map snd (splitLines getRest)
                                        getLine = (takeWhile (/='\n') str)
                                        getRest =  (dropWhile (=='\n') (dropWhile (/='\n') str))

工作正常,但我想我也需要空行。

splitLines "test\nthis\nstring\n" should be
[(0,"test"),(1,"this"),(2,"string"),(3,"")]

不完全确定我怎么能做到这一点。有任何想法吗? 我需要用其他东西重写它吗?

我应该使用像 foldr 这样的高阶函数吗? 谢谢。

终于搞定了,谢谢。

splitLines :: String -> Document
splitLines "" = [(0,"")]
splitLines str = zip [0..(length listStr)] listStr
                                    where 
                                        listStr = [getLine] ++ map snd (splitLines getRest)
                                        getLine = takeWhile (/='\n') str
                                        getRest = tail (dropWhile (/='\n') str)

【问题讨论】:

  • 为什么你的元组需要复制索引? lines 不是你想要的吗?
  • 不能使用线条。必须创建我们自己的线条功能。我怎么能使用索引?不知道该怎么做。

标签: list string haskell


【解决方案1】:

它正在丢弃空行,因为您正在执行 dropWhile (=='\n)`,从字符串的开头删除所有换行符。

要保留空行,您只能删除一个换行符。最简单的方法是使用模式匹配:

getRest = case (dropWhile (/='\n') str) of
              (_:xs) -> xs
              [] -> []

【讨论】:

    【解决方案2】:

    如上所述,当您从字符串的开头修剪换行符时,您不会得到空行。如果对splitLines 稍作重构,就会更容易看到这一点。既然你不能使用lines,我会先创建一个简单的split函数(你也可以使用Data.List.Split):

    split :: (Eq a) => a -> [a] -> [[a]]
    split a [] = [[]]
    split a lst = (\(xs, y:ys) -> [xs] ++ split a ys) $ break (==a) lst
    

    有了这个功能,splitLines就很简单了:

    splitLines :: String -> Document
    splitLines [] = []
    splitLines str = zip [0..] $ split '\n' str 
    

    【讨论】:

    • 老实说,我什至不认为我可以使用拆分和中断。但我终于明白了。谢谢。
    猜你喜欢
    • 2019-06-05
    • 2015-03-30
    • 1970-01-01
    • 2012-05-20
    • 2012-02-09
    • 1970-01-01
    • 2021-02-17
    • 2020-06-27
    相关资源
    最近更新 更多