-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.ml
102 lines (80 loc) · 2.57 KB
/
utils.ml
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
module Tools :
sig
val first_elts : 'a list -> int -> 'a list
val last_elts : 'a list -> int -> 'a list
val split : 'a list -> 'a list * 'a list
val generic_completion : 'a -> 'a list -> int -> 'a list
val false_completion : bool list -> int -> bool list
val truth_table_printer : bool list -> unit
val truth_table_printer_2 : bool list -> unit list
val file_display : string -> unit
end = struct
let rec first_elts list n =
match list with
| [] -> []
| x :: r -> if n <= 0 then [] else if n == 1 then [x] else x :: first_elts r (n-1)
;;
let rec last_elts list n =
match list with
| [] -> []
| x :: r -> if n == List.length r then r else last_elts r n
;;
let rec split list =
let len = List.length list in
let len2 = len / 2 in
(first_elts list len2, last_elts list (len-len2))
;;
let generic_completion default_value list n =
let len = List.length list in
let completed_list = first_elts list n in
if n <= len then
completed_list
else
let tmp_list = List.init (n-len) (fun x -> default_value) in
List.append completed_list tmp_list
;;
let false_completion = generic_completion false;;
let rec truth_table_print fmt = function
| [] -> ()
| [x] -> Format.fprintf fmt "%B" x
| x :: r -> Format.fprintf fmt "%B, %a" x truth_table_print r
;;
let truth_table_printer ttable =
Format.printf "[%a]@." truth_table_print ttable
;;
let bool_print_2 exp b =
match b with
| false -> ()
| true -> Format.printf "2^%d + " exp
;;
let truth_table_printer_2 ttable =
List.mapi bool_print_2 ttable
;;
let file_display file_name =
let cmd = Format.sprintf "cat %s" file_name in
begin try ignore (Sys.command cmd) with _ -> () end;
end;;
module Math = struct
let increment = fun x -> x + 1;;
let ref_increment = fun x -> x := !x + 1;;
let rec power nb ex =
match ex with
| 0 -> 1
| n -> nb * power nb (ex-1)
;;
let power_2 ex = power 2 ex;;
let is_power_2 elt = Float.is_integer (Float.log2 elt);;
let euclidean_division divider dividend =
if divider = 0 then raise Division_by_zero else
(dividend / divider, dividend mod divider);;
let euclidean_division_2 = euclidean_division 2;;
let rec decomposition elt =
match elt with
| 0 -> []
| i ->
let (q,r) = euclidean_division_2 i in
if r == 0 then false :: decomposition q
else true :: decomposition q
;;
let truth_table elt n = Tools.false_completion (decomposition elt) n;;
end;;