Splitting lists

Haskell

Public Domain

Split a list at all occurrences of an element or a sublist

Download (right click, save as, rename as appropriate)

Embed

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import List

splitAtElem :: Eq a => a -> [a] -> [[a]]
splitAtElem _ [] = [[]]
splitAtElem e xs = pre : if null post then [] else splitAtElem e (tail post)
 where (pre, post) = break (== e) xs

splitAtSublist :: Eq a => [a] -> [a] -> [[a]]
splitAtSublist _ [] = [[]]
splitAtSublist sub xs = case findSublist sub xs of
 Just n  -> take n xs : splitAtSublist sub (drop (length sub + n) xs)
 Nothing -> [xs]

findSublist :: Eq a => [a] -> [a] -> Maybe Int
findSublist sub list = find (\i -> isPrefixOf sub (drop i list))
 (elemIndices (head sub) list)