Source file Sheet.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
module Cells = Map.Make (struct
type t = Formula.cell
let compare = compare
end)
type value = Number of float | Text of string | Error of string | Empty
type t = {
raws : string Cells.t;
contents : Formula.content Cells.t;
values : value Cells.t;
reads : Formula.cell list Cells.t;
read_by : Formula.cell list Cells.t;
last_recalculated : int;
}
let empty =
{
raws = Cells.empty;
contents = Cells.empty;
values = Cells.empty;
reads = Cells.empty;
read_by = Cells.empty;
last_recalculated = 0;
}
let raw t c = match Cells.find_opt c t.raws with Some s -> s | None -> ""
let value t c = match Cells.find_opt c t.values with Some v -> v | None -> Empty
let cells t = Cells.bindings t.raws |> List.map fst
let recalculated t = t.last_recalculated
let show = function
| Empty -> ""
| Text s -> s
| Error why -> "#" ^ why
| Number f ->
if Float.is_integer f && Float.abs f < 1e15 then Printf.sprintf "%.0f" f
else Printf.sprintf "%g" f
let number_of : value -> (float, string) result = function
| Number f -> Result.Ok f
| Empty -> Result.Ok 0.
| Text _ -> Result.Error "text"
| Error why -> Result.Error why
let rec numbers t (e : Formula.expr) : (float list, string) result =
match e with
| Formula.Range ((c1, r1), (c2, r2)) ->
let out = ref [] and bad = ref None in
for col = min c1 c2 to max c1 c2 do
for row = min r1 r2 to max r1 r2 do
match value t (col, row) with
| Number f -> out := f :: !out
| Empty | Text _ -> ()
| Error why -> if !bad = None then bad := Some why
done
done;
(match !bad with Some why -> Result.Error why | None -> Result.Ok (List.rev !out))
| e -> (
match number_of (eval t e) with
| Result.Ok f -> Result.Ok [ f ]
| Result.Error why -> Result.Error why)
and eval t (e : Formula.expr) : value =
let arith f a b =
match (number_of (eval t a), number_of (eval t b)) with
| Result.Ok x, Result.Ok y -> f x y
| Result.Error why, _ | _, Result.Error why -> Error why
in
match e with
| Formula.Number f -> Number f
| Formula.Ref c -> value t c
| Formula.Range _ -> Error "range"
| Formula.Unary ('-', e) -> (
match number_of (eval t e) with
| Result.Ok f -> Number (-.f)
| Result.Error why -> Error why)
| Formula.Unary (_, e) -> eval t e
| Formula.Binop ('+', a, b) -> arith (fun x y -> Number (x +. y)) a b
| Formula.Binop ('-', a, b) -> arith (fun x y -> Number (x -. y)) a b
| Formula.Binop ('*', a, b) -> arith (fun x y -> Number (x *. y)) a b
| Formula.Binop ('/', a, b) ->
arith (fun x y -> if y = 0. then Error "div0" else Number (x /. y)) a b
| Formula.Binop (c, _, _) -> Error (Printf.sprintf "op%c" c)
| Formula.Call (name, args) -> (
let gathered : (float list, string) result =
List.fold_left
(fun (acc : (float list, string) result) arg ->
match (acc, numbers t arg) with
| Result.Error why, _ -> Result.Error why
| _, Result.Error why -> Result.Error why
| Result.Ok all, Result.Ok some -> Result.Ok (all @ some))
(Result.Ok []) args
in
match gathered with
| Result.Error why -> Error why
| Result.Ok ns -> (
let sum = List.fold_left ( +. ) 0. ns in
match (name, ns) with
| "SUM", _ -> Number sum
| "COUNT", _ -> Number (float_of_int (List.length ns))
| "PRODUCT", _ -> Number (List.fold_left ( *. ) 1. ns)
| "AVERAGE", [] -> Error "empty"
| "AVERAGE", _ -> Number (sum /. float_of_int (List.length ns))
| "MIN", [] | "MAX", [] -> Error "empty"
| "MIN", n :: rest -> Number (List.fold_left min n rest)
| "MAX", n :: rest -> Number (List.fold_left max n rest)
| _ -> Error ("fn" ^ name)))
let value_of_content t = function
| Formula.Blank -> Empty
| Formula.Value f -> Number f
| Formula.Text s -> Text s
| Formula.Invalid why -> Error why
| Formula.Formula e -> eval t e
let readers t c = match Cells.find_opt c t.read_by with Some l -> l | None -> []
let downstream t start =
let seen = ref [] in
let rec go c =
if not (List.mem c !seen) then begin
seen := c :: !seen;
List.iter go (readers t c)
end
in
go start;
!seen
let recompute t dirty =
let waiting_for c =
match Cells.find_opt c t.reads with
| None -> []
| Some l -> List.filter (fun d -> List.mem d dirty) l
in
let pending = ref (List.map (fun c -> (c, waiting_for c)) dirty) in
let t = ref t in
let done_ = ref 0 in
let rec rounds () =
let ready, blocked = List.partition (fun (_, waits) -> waits = []) !pending in
if ready <> [] then begin
List.iter
(fun (c, _) ->
let v =
match Cells.find_opt c !t.contents with
| Some content -> value_of_content !t content
| None -> Empty
in
t := { !t with values = Cells.add c v !t.values };
incr done_)
ready;
let computed = List.map fst ready in
pending := List.map (fun (c, waits) -> (c, List.filter (fun d -> not (List.mem d computed)) waits)) blocked;
rounds ()
end
in
rounds ();
let t =
List.fold_left
(fun t (c, _) -> { t with values = Cells.add c (Error "cycle") t.values })
!t !pending
in
{ t with last_recalculated = !done_ + List.length !pending }
let store c text t =
let content = Formula.content_of text in
let old_reads = match Cells.find_opt c t.reads with Some l -> l | None -> [] in
let new_reads = match content with Formula.Formula e -> Formula.refs e | _ -> [] in
let read_by =
List.fold_left
(fun m d ->
let others = List.filter (fun x -> x <> c) (match Cells.find_opt d m with Some l -> l | None -> []) in
Cells.add d others m)
t.read_by old_reads
in
let read_by =
List.fold_left
(fun m d ->
let others = match Cells.find_opt d m with Some l -> l | None -> [] in
Cells.add d (c :: others) m)
read_by new_reads
in
{
t with
raws = (if String.trim text = "" then Cells.remove c t.raws else Cells.add c text t.raws);
contents = Cells.add c content t.contents;
reads = Cells.add c new_reads t.reads;
read_by;
}
let set c text t =
let t = store c text t in
recompute t (downstream t c)
type order = Rows | Columns
let recalculate order t =
let cs = cells t in
let ordered =
List.sort
(fun (c1, r1) (c2, r2) ->
match order with
| Rows -> compare (r1, c1) (r2, c2)
| Columns -> compare (c1, r1) (c2, r2))
cs
in
let t =
List.fold_left
(fun t c ->
match Cells.find_opt c t.contents with
| Some content -> { t with values = Cells.add c (value_of_content t content) t.values }
| None -> t)
t ordered
in
{ t with last_recalculated = List.length ordered }
let to_string t =
cells t
|> List.map (fun c -> Printf.sprintf "%s\t%s" (Formula.name_of_cell c) (raw t c))
|> String.concat "\n"
let of_string s =
String.split_on_char '\n' s
|> List.fold_left
(fun t line ->
match String.index_opt line '\t' with
| None -> t
| Some i -> (
let name = String.sub line 0 i in
let text = String.sub line (i + 1) (String.length line - i - 1) in
match Formula.cell_of_name (String.trim name) with
| Some c -> set c text t
| None -> t))
empty