findSublist.hs

Haskell

Public Domain

Find a sublist/substring in a list/string

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

Embed

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

-- |@findSublist sub list@ returns the index of the start of the first
-- occurrence of @sub@ inside @list@, or @Nothing@ if there is none.
findSublist :: Eq a => [a] -> [a] -> Maybe Int
findSublist sub list = find (\i -> isPrefixOf sub (drop i list))
 (elemIndices (head sub) list)

-- |@findSublists sub list@ returns the indices of the beginnings of all
-- occurrences (including overlapping ones) of @sub@ inside @list@.
findSublists :: Eq a => [a] -> [a] -> [Int]
findSublists sub list = filter (\i -> isPrefixOf sub (drop i list))
 (elemIndices (head sub) list)