Haskell:字符串拆分。学习算法

时间:2012-04-11 08:00:07

标签: haskell

我已经看到了关于缺少分裂功能的其他线程但是我不想偷看,因为我这样做是为了学习目的并且想要弄清楚自己。所以这就是:

split :: Char -> String -> [String]
split c xs | null f = []
           | otherwise = f : split c s'
  where (f,s) = break (== c) xs
        s' | null s = s
           | otherwise = tail s

它似乎工作正常(请告诉我它是否有任何问题)但是当我使用不在字符串中的拆分字符时,该函数返回一个包含原始字符串的单个元素的列表,而我想要它返回一个空列表。我无法弄明白该怎么做。

任何想法?。

1 个答案:

答案 0 :(得分:1)

您可以简单地编写一个包装函数,更改原始函数的结果:

split' x xs = go (split x xs)  where
   go [_] = []
   go ys = ys

编写分割函数的方法有很多种,例如

split x xs = foldl' go [[]] xs where
   go (ys:yss) y | y == x = []:ys:yss
                 | otherwise = (y:ys):yss    

 import Data.List 

 split x xs = map tail $ groupBy (const (/=x)) (x:xs)