1
(***********************************************************************)
5
(* Pierre Weis, projet Cristal, INRIA Rocquencourt *)
7
(* Copyright 2001 Institut National de Recherche en Informatique et *)
8
(* en Automatique. All rights reserved. This file is distributed *)
9
(* only by permission. *)
11
(***********************************************************************)
13
(* Find the first occurrence of string [p] (the so-called ``pattern'')
16
Knuth-Morris-Pratt algorithm following Sedgewick's book "Algorithms".
17
The Caml code was proved correct in the Coq Proof Assistant.
18
Based on a mail to the Caml list by Jean-Christophe FILLIATRE. *)
21
let m = String.length p in
22
let next = Array.create m 0 in
23
let i = ref 1 and j = ref 0 in
25
if p.[!i] = p.[!j] then begin incr i; incr j; next.(!i) <- !j end else
26
if !j = 0 then begin incr i; next.(!i) <- 0 end else j := next.(!j)
31
let next = init_next p
32
and m = String.length p in
34
let n = String.length s
37
while !j < m && !i < n do
38
if s.[!i] = p.[!j] then begin incr i; incr j end else
39
if !j = 0 then incr i else j := next.(!j)
41
if !j >= m then !i - m else raise Not_found;;
46
print_string "Match found at character ";
51
print_string "Pattern ";
53
print_string " does not match string ";
60
"Usage: kmp <pat> <str>\n\
61
returns the index of the first occurrence of <pat> in string <str>\n";
65
let args = Sys.argv in
66
if Array.length args < 2 then usage () else
68
and s = Sys.argv.(2) in
71
if !Sys.interactive then () else main ();;