How to split a string in Haskell?

后端 未结 13 1577
日久生厌
日久生厌 2020-11-28 03:08

Is there a standard way to split a string in Haskell?

lines and words work great from splitting on a space or newline, but surely there is

13条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 03:58

    I started learning Haskell yesterday, so correct me if I'm wrong but:

    split :: Eq a => a -> [a] -> [[a]]
    split x y = func x y [[]]
        where
            func x [] z = reverse $ map (reverse) z
            func x (y:ys) (z:zs) = if y==x then 
                func x ys ([]:(z:zs)) 
            else 
                func x ys ((y:z):zs)
    

    gives:

    *Main> split ' ' "this is a test"
    ["this","is","a","test"]
    

    or maybe you wanted

    *Main> splitWithStr  " and " "this and is and a and test"
    ["this","is","a","test"]
    

    which would be:

    splitWithStr :: Eq a => [a] -> [a] -> [[a]]
    splitWithStr x y = func x y [[]]
        where
            func x [] z = reverse $ map (reverse) z
            func x (y:ys) (z:zs) = if (take (length x) (y:ys)) == x then
                func x (drop (length x) (y:ys)) ([]:(z:zs))
            else
                func x ys ((y:z):zs)
    

提交回复
热议问题