1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
module String = struct
let is_prefix ~prefix str =
let pl = String.length prefix in
if String.length str < pl then
false
else
String.sub str 0 (String.length prefix) = prefix
let is_suffix ~suffix str =
let pl = String.length suffix in
if String.length str < pl then
false
else
String.sub str (String.length str - pl) pl = suffix
let cut sep str =
try
let idx = String.index str sep
and l = String.length str
in
let sidx = succ idx in
Some (String.sub str 0 idx, String.sub str sidx (l - sidx))
with
Not_found -> None
let cuts sep str =
let rec doit acc s =
match cut sep s with
| None -> List.rev (s :: acc)
| Some (a, b) -> doit (a :: acc) b
in
doit [] str
let slice ?(start = 0) ?stop str =
let stop = match stop with
| None -> String.length str
| Some x -> x
in
let len = stop - start in
String.sub str start len
let count_common_suffix x y =
let rec loop ~x ~y acc ix iy =
if ix >= 0 && iy >= 0 &&
String.unsafe_get x ix = (String.unsafe_get y iy : char) then
loop ~x ~y (acc + 1) (ix - 1) (iy - 1)
else
acc
in
let len_x = String.length x in
let len_y = String.length y in
loop ~x ~y 0 (len_x - 1) (len_y - 1)
end
module List = struct
let rec last = function
| [] -> invalid_arg "List.last"
| [x] -> x
| _::xs -> last xs
let rev_cut idx l =
let rec aux acc idx = function
| l when idx = 0 -> (acc, l)
| [] -> invalid_arg "List.cut"
| x::xs -> aux (x :: acc) (idx - 1) xs
in
aux [] idx l
end