Knuth-Morris-Pratt matcher type
This type is used to keep data for running the Knuth-Morris-Pratt (KMP) list matching algorithm. KMP is a linear time algorithm to locate all contiguous sublists of a list that match a given pattern. Generating the algorithm data is also linear in the length of the pattern but the data can be re-used to match the same pattern over multiple lists.
The KMP data for a pattern can be generated using Matcher.ofList
. Then Matcher.find?
and
Matcher.findAll
can be used to run the algorithm on an input list.
def m := Matcher.ofList [0,1,1,0]
#eval Option.isSome <| m.find? [2,1,1,0,1,1,2] -- false
#eval Option.isSome <| m.find? [0,0,1,1,0,0] -- true
#eval Array.size <| m.findAll [0,1,1,0,1,1,0] -- 2
#eval Array.size <| m.findAll [0,1,1,0,1,1,0,1,1,0] -- 3
- pattern : List α
The pattern for the matcher
Instances For
Make KMP matcher from list pattern.
Equations
- List.Matcher.ofList pattern = { toMatcher := Array.Matcher.ofStream pattern, pattern := pattern }
Instances For
Find all start and end positions of all infix sublists of l
matching m.pattern
.
The sublists may be overlapping.
Equations
- m.findAll l = List.Matcher.findAll.loop m (l, 0) m.toMatcher #[]
Instances For
Accumulator loop for List.Matcher.findAll
Find the start and end positions of the first infix sublist of l
matching m.pattern
,
or none
if there is no such sublist.
Equations
Instances For
Returns all the start and end positions of all infix sublists of of l
that match pattern
.
The sublists may be overlapping.
Equations
- l.findAllInfix pattern = (List.Matcher.ofList pattern).findAll l
Instances For
Returns the start and end positions of the first infix sublist of l
that matches pattern
,
or none
if there is no such sublist.
Equations
- l.findInfix? pattern = (List.Matcher.ofList pattern).find? l