Debian Codegraph @

clib/range.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 type 'a tree =
12 | Leaf of 'a
13 | Node of 'a * 'a tree * 'a tree
14
15 type 'a t = Nil | Cons of int * 'a tree * 'a t
16
17 let oob () = invalid_arg "index out of bounds"
18
19 let empty = Nil
20
21 let cons x l = match l with
22 | Cons (h1, t1, Cons (h2, t2, rem)) ->
23 if Int.equal h1 h2 then Cons (1 + h1 + h2, Node (x, t1, t2), rem)
24 else Cons (1, Leaf x, l)
25 | _ -> Cons (1, Leaf x, l)
26
27 let is_empty = function
28 | Nil -> true
29 | _ -> false
30
31 let rec tree_get h t i = match t with
32 | Leaf x ->
33 if i = 0 then x else oob ()
34 | Node (x, t1, t2) ->
35 if i = 0 then x
36 else
37 let h = h / 2 in
38 if i <= h then tree_get h t1 (i - 1) else tree_get h t2 (i - h - 1)
39
40 let rec get l i = match l with
41 | Nil -> oob ()
42 | Cons (h, t, rem) ->
43 if i < h then tree_get h t i else get rem (i - h)
44
45 let length l =
46 let rec length accu = function
47 | Nil -> accu
48 | Cons (h, _, l) -> length (h + accu) l
49 in
50 length 0 l
51
52 let rec tree_map f = function
53 | Leaf x -> Leaf (f x)
54 | Node (x, t1, t2) -> Node (f x, tree_map f t1, tree_map f t2)
55
56 let rec map f = function
57 | Nil -> Nil
58 | Cons (h, t, l) -> Cons (h, tree_map f t, map f l)
59
60 let rec tree_fold_left f accu = function
61 | Leaf x -> f accu x
62 | Node (x, t1, t2) ->
63 tree_fold_left f (tree_fold_left f (f accu x) t1) t2
64
65 let rec fold_left f accu = function
66 | Nil -> accu
67 | Cons (_, t, l) -> fold_left f (tree_fold_left f accu t) l
68
69 let rec tree_fold_right f t accu = match t with
70 | Leaf x -> f x accu
71 | Node (x, t1, t2) ->
72 f x (tree_fold_right f t1 (tree_fold_right f t2 accu))
73
74 let rec fold_right f l accu = match l with
75 | Nil -> accu
76 | Cons (_, t, l) -> tree_fold_right f t (fold_right f l accu)
77
78 let hd = function
79 | Nil -> failwith "hd"
80 | Cons (_, Leaf x, _) -> x
81 | Cons (_, Node (x, _, _), _) -> x
82
83 let tl = function
84 | Nil -> failwith "tl"
85 | Cons (_, Leaf _, l) -> l
86 | Cons (h, Node (_, t1, t2), l) ->
87 let h = h / 2 in
88 Cons (h, t1, Cons (h, t2, l))
89
90 let rec skipn n l =
91 if n = 0 then l
92 else if is_empty l then failwith "List.skipn"
93 else skipn (pred n) (tl l)