2012-04-11 110 views
1

我已经看过关于缺少分裂函数的其他线程,但我不想偷看,因为我这样做是为了学习的目的,并想弄清楚我自己。所以在这里,它是: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

你可以简单地写一个包装函数,改变你原来的结果:

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) 
+0

+1。原始函数的主要部分也可以写成break(== c)>>> second(split c。drop 1)>>> uncurry(:)',但是它仍然需要检查'xs '是空的。 – Vitus 2012-04-11 08:54:58

+0

非常好的例子。很高兴学习新的东西。谢谢。 – 2012-04-12 01:52:12