Source file seq.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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
(**************************************************************************)
(*                                                                        *)
(*                                 OCaml                                  *)
(*                                                                        *)
(*                 Simon Cruanes                                          *)
(*                                                                        *)
(*   Copyright 2017 Institut National de Recherche en Informatique et     *)
(*     en Automatique.                                                    *)
(*                                                                        *)
(*   All rights reserved.  This file is distributed under the terms of    *)
(*   the GNU Lesser General Public License version 2.1, with the          *)
(*   special exception on linking described in the file LICENSE.          *)
(*                                                                        *)
(**************************************************************************)

(* Module [Seq]: functional iterators *)

type +'a node =
  | Nil
  | Cons of 'a * 'a t

and 'a t = unit -> 'a node

let empty () = Nil

let return x () = Cons (x, empty)

let cons x next () = Cons (x, next)

let rec append seq1 seq2 () =
  match seq1() with
  | Nil -> seq2()
  | Cons (x, next) -> Cons (x, append next seq2)

let rec map f seq () = match seq() with
  | Nil -> Nil
  | Cons (x, next) -> Cons (f x, map f next)

let rec filter_map f seq () = match seq() with
  | Nil -> Nil
  | Cons (x, next) ->
      match f x with
        | None -> filter_map f next ()
        | Some y -> Cons (y, filter_map f next)

let rec filter f seq () = match seq() with
  | Nil -> Nil
  | Cons (x, next) ->
      if f x
      then Cons (x, filter f next)
      else filter f next ()

let rec concat seq () = match seq () with
  | Nil -> Nil
  | Cons (x, next) ->
     append x (concat next) ()

let rec flat_map f seq () = match seq () with
  | Nil -> Nil
  | Cons (x, next) ->
    append (f x) (flat_map f next) ()

let concat_map = flat_map

let rec fold_left f acc seq =
  match seq () with
    | Nil -> acc
    | Cons (x, next) ->
        let acc = f acc x in
        fold_left f acc next

let rec iter f seq =
  match seq () with
    | Nil -> ()
    | Cons (x, next) ->
        f x;
        iter f next

let rec unfold f u () =
  match f u with
  | None -> Nil
  | Some (x, u') -> Cons (x, unfold f u')

let is_empty xs =
  match xs() with
  | Nil ->
      true
  | Cons (_, _) ->
      false

let uncons xs =
  match xs() with
  | Cons (x, xs) ->
      Some (x, xs)
  | Nil ->
      None



let rec length_aux accu xs =
  match xs() with
  | Nil ->
      accu
  | Cons (_, xs) ->
      length_aux (accu + 1) xs

let[@inline] length xs =
  length_aux 0 xs

let rec iteri_aux f i xs =
  match xs() with
  | Nil ->
      ()
  | Cons (x, xs) ->
      f i x;
      iteri_aux f (i+1) xs

let[@inline] iteri f xs =
  iteri_aux f 0 xs

let rec fold_lefti_aux f accu i xs =
  match xs() with
  | Nil ->
      accu
  | Cons (x, xs) ->
      let accu = f accu i x in
      fold_lefti_aux f accu (i+1) xs

let[@inline] fold_lefti f accu xs =
  fold_lefti_aux f accu 0 xs

let rec for_all p xs =
  match xs() with
  | Nil ->
      true
  | Cons (x, xs) ->
      p x && for_all p xs

let rec exists p xs =
  match xs() with
  | Nil ->
      false
  | Cons (x, xs) ->
      p x || exists p xs

let rec find p xs =
  match xs() with
  | Nil ->
      None
  | Cons (x, xs) ->
      if p x then Some x else find p xs

let find_index p xs =
  let rec aux i xs = match xs() with
    | Nil ->
        None
    | Cons (x, xs) ->
        if p x then Some i else aux (i+1) xs in
  aux 0 xs

let rec find_map f xs =
  match xs() with
  | Nil ->
      None
  | Cons (x, xs) ->
      match f x with
      | None ->
          find_map f xs
      | Some _ as result ->
          result

let find_mapi f xs =
  let rec aux i xs = match xs() with
    | Nil ->
        None
    | Cons (x, xs) ->
        match f i x with
        | None ->
            aux (i+1) xs
        | Some _ as result ->
            result in
  aux 0 xs

(* [iter2], [fold_left2], [for_all2], [exists2], [map2], [zip] work also in
   the case where the two sequences have different lengths. They stop as soon
   as one sequence is exhausted. Their behavior is slightly asymmetric: when
   [xs] is empty, they do not force [ys]; however, when [ys] is empty, [xs] is
   forced, even though the result of the function application [xs()] turns out
   to be useless. *)

let rec iter2 f xs ys =
  match xs() with
  | Nil ->
      ()
  | Cons (x, xs) ->
      match ys() with
      | Nil ->
          ()
      | Cons (y, ys) ->
          f x y;
          iter2 f xs ys

let rec fold_left2 f accu xs ys =
  match xs() with
  | Nil ->
      accu
  | Cons (x, xs) ->
      match ys() with
      | Nil ->
          accu
      | Cons (y, ys) ->
          let accu = f accu x y in
          fold_left2 f accu xs ys

let rec for_all2 f xs ys =
  match xs() with
  | Nil ->
      true
  | Cons (x, xs) ->
      match ys() with
      | Nil ->
          true
      | Cons (y, ys) ->
          f x y && for_all2 f xs ys

let rec exists2 f xs ys =
  match xs() with
  | Nil ->
      false
  | Cons (x, xs) ->
      match ys() with
      | Nil ->
          false
      | Cons (y, ys) ->
          f x y || exists2 f xs ys

let rec equal eq xs ys =
  match xs(), ys() with
  | Nil, Nil ->
      true
  | Cons (x, xs), Cons (y, ys) ->
      eq x y && equal eq xs ys
  | Nil, Cons (_, _)
  | Cons (_, _), Nil ->
      false

let rec compare cmp xs ys =
  match xs(), ys() with
  | Nil, Nil ->
      0
  | Cons (x, xs), Cons (y, ys) ->
      let c = cmp x y in
      if c <> 0 then c else compare cmp xs ys
  | Nil, Cons (_, _) ->
      -1
  | Cons (_, _), Nil ->
      +1



(* [init_aux f i j] is the sequence [f i, ..., f (j-1)]. *)

let rec init_aux f i j () =
  if i < j then begin
    Cons (f i, init_aux f (i + 1) j)
  end
  else
    Nil

let init n f =
  if n < 0 then
    invalid_arg "Seq.init"
  else
    init_aux f 0 n

let rec repeat x () =
  Cons (x, repeat x)

let rec forever f () =
  Cons (f(), forever f)

(* This preliminary definition of [cycle] requires the sequence [xs]
   to be nonempty. Applying it to an empty sequence would produce a
   sequence that diverges when it is forced. *)

let rec cycle_nonempty xs () =
  append xs (cycle_nonempty xs) ()

(* [cycle xs] checks whether [xs] is empty and, if so, returns an empty
   sequence. Otherwise, [cycle xs] produces one copy of [xs] followed
   with the infinite sequence [cycle_nonempty xs]. Thus, the nonemptiness
   check is performed just once. *)

let cycle xs () =
  match xs() with
  | Nil ->
      Nil
  | Cons (x, xs') ->
      Cons (x, append xs' (cycle_nonempty xs))

(* [iterate1 f x] is the sequence [f x, f (f x), ...].
   It is equivalent to [tail (iterate f x)].
   [iterate1] is used as a building block in the definition of [iterate]. *)

let rec iterate1 f x () =
  let y = f x in
  Cons (y, iterate1 f y)

(* [iterate f x] is the sequence [x, f x, ...]. *)

(* The reason why we give this slightly indirect definition of [iterate],
   as opposed to the more naive definition that may come to mind, is that
   we are careful to avoid evaluating [f x] until this function call is
   actually necessary. The naive definition (not shown here) computes the
   second argument of the sequence, [f x], when the first argument is
   requested by the user. *)

let iterate f x =
  cons x (iterate1 f x)



let rec mapi_aux f i xs () =
  match xs() with
  | Nil ->
      Nil
  | Cons (x, xs) ->
      Cons (f i x, mapi_aux f (i+1) xs)

let[@inline] mapi f xs =
  mapi_aux f 0 xs

(* [tail_scan f s xs] is equivalent to [tail (scan f s xs)].
   [tail_scan] is used as a building block in the definition of [scan]. *)

(* This slightly indirect definition of [scan] is meant to avoid computing
   elements too early; see the above comment about [iterate1] and [iterate]. *)

let rec tail_scan f s xs () =
  match xs() with
  | Nil ->
      Nil
  | Cons (x, xs) ->
      let s = f s x in
      Cons (s, tail_scan f s xs)

let scan f s xs =
  cons s (tail_scan f s xs)

(* [take] is defined in such a way that [take 0 xs] returns [empty]
   immediately, without allocating any memory. *)

let rec take_aux n xs =
  if n = 0 then
    empty
  else
    fun () ->
      match xs() with
      | Nil ->
          Nil
      | Cons (x, xs) ->
          Cons (x, take_aux (n-1) xs)

let take n xs =
  if n < 0 then invalid_arg "Seq.take";
  take_aux n xs

(* [force_drop n xs] is equivalent to [drop n xs ()].
   [force_drop n xs] requires [n > 0].
   [force_drop] is used as a building block in the definition of [drop]. *)

let rec force_drop n xs =
  match xs() with
  | Nil ->
      Nil
  | Cons (_, xs) ->
      let n = n - 1 in
      if n = 0 then
        xs()
      else
        force_drop n xs

(* [drop] is defined in such a way that [drop 0 xs] returns [xs] immediately,
   without allocating any memory. *)

let drop n xs =
  if n < 0 then invalid_arg "Seq.drop"
  else if n = 0 then
    xs
  else
    fun () ->
      force_drop n xs

let rec take_while p xs () =
  match xs() with
  | Nil ->
      Nil
  | Cons (x, xs) ->
      if p x then Cons (x, take_while p xs) else Nil

let rec drop_while p xs () =
  match xs() with
  | Nil ->
      Nil
  | Cons (x, xs) as node ->
      if p x then drop_while p xs () else node

let rec group eq xs () =
  match xs() with
  | Nil ->
      Nil
  | Cons (x, xs) ->
      Cons (cons x (take_while (eq x) xs), group eq (drop_while (eq x) xs))

exception Forced_twice

module Suspension = struct

  type 'a suspension =
    unit -> 'a

  (* Conversions. *)

  let to_lazy : 'a suspension -> 'a Lazy.t =
    Lazy.from_fun
    (* fun s -> lazy (s()) *)

  let from_lazy (s : 'a Lazy.t) : 'a suspension =
    fun () -> Lazy.force s

  (* [memoize] turns an arbitrary suspension into a persistent suspension. *)

  let memoize (s : 'a suspension) : 'a suspension =
    from_lazy (to_lazy s)

  (* [failure] is a suspension that fails when forced. *)

  let failure : _ suspension =
    fun () ->
      (* A suspension created by [once] has been forced twice. *)
      raise Forced_twice

  (* If [f] is a suspension, then [once f] is a suspension that can be forced
     at most once. If it is forced more than once, then [Forced_twice] is
     raised. *)

  let once (f : 'a suspension) : 'a suspension =
    let action = Atomic.make f in
    fun () ->
      (* Get the function currently stored in [action], and write the
         function [failure] in its place, so the next access will result
         in a call to [failure()]. *)
      let f = Atomic.exchange action failure in
      f()

end (* Suspension *)

let rec memoize xs =
  Suspension.memoize (fun () ->
    match xs() with
    | Nil ->
        Nil
    | Cons (x, xs) ->
        Cons (x, memoize xs)
  )

let rec once xs =
  Suspension.once (fun () ->
    match xs() with
    | Nil ->
        Nil
    | Cons (x, xs) ->
        Cons (x, once xs)
  )


let rec zip xs ys () =
  match xs() with
  | Nil ->
      Nil
  | Cons (x, xs) ->
      match ys() with
      | Nil ->
          Nil
      | Cons (y, ys) ->
          Cons ((x, y), zip xs ys)

let rec map2 f xs ys () =
  match xs() with
  | Nil ->
      Nil
  | Cons (x, xs) ->
      match ys() with
      | Nil ->
          Nil
      | Cons (y, ys) ->
          Cons (f x y, map2 f xs ys)

let rec interleave xs ys () =
  match xs() with
  | Nil ->
      ys()
  | Cons (x, xs) ->
      Cons (x, interleave ys xs)

(* [sorted_merge1l cmp x xs ys] is equivalent to
     [sorted_merge cmp (cons x xs) ys].

   [sorted_merge1r cmp xs y ys] is equivalent to
     [sorted_merge cmp xs (cons y ys)].

   [sorted_merge1 cmp x xs y ys] is equivalent to
     [sorted_merge cmp (cons x xs) (cons y ys)].

   These three functions are used as building blocks in the definition
   of [sorted_merge]. *)

let rec sorted_merge1l cmp x xs ys () =
  match ys() with
  | Nil ->
      Cons (x, xs)
  | Cons (y, ys) ->
      sorted_merge1 cmp x xs y ys

and sorted_merge1r cmp xs y ys () =
  match xs() with
  | Nil ->
      Cons (y, ys)
  | Cons (x, xs) ->
      sorted_merge1 cmp x xs y ys

and sorted_merge1 cmp x xs y ys =
  if cmp x y <= 0 then
    Cons (x, sorted_merge1r cmp xs y ys)
  else
    Cons (y, sorted_merge1l cmp x xs ys)

let sorted_merge cmp xs ys () =
  match xs(), ys() with
    | Nil, Nil ->
        Nil
    | Nil, c
    | c, Nil ->
        c
    | Cons (x, xs), Cons (y, ys) ->
        sorted_merge1 cmp x xs y ys


let rec map_fst xys () =
  match xys() with
  | Nil ->
      Nil
  | Cons ((x, _), xys) ->
      Cons (x, map_fst xys)

let rec map_snd xys () =
  match xys() with
  | Nil ->
      Nil
  | Cons ((_, y), xys) ->
      Cons (y, map_snd xys)

let unzip xys =
  map_fst xys, map_snd xys

let split =
  unzip

(* [filter_map_find_left_map f xs] is equivalent to
   [filter_map Either.find_left (map f xs)]. *)

let rec filter_map_find_left_map f xs () =
  match xs() with
  | Nil ->
      Nil
  | Cons (x, xs) ->
      match f x with
      | Either.Left y ->
          Cons (y, filter_map_find_left_map f xs)
      | Either.Right _ ->
          filter_map_find_left_map f xs ()

let rec filter_map_find_right_map f xs () =
  match xs() with
  | Nil ->
      Nil
  | Cons (x, xs) ->
      match f x with
      | Either.Left _ ->
          filter_map_find_right_map f xs ()
      | Either.Right z ->
          Cons (z, filter_map_find_right_map f xs)

let partition_map f xs =
  filter_map_find_left_map f xs,
  filter_map_find_right_map f xs

let partition p xs =
  filter p xs, filter (fun x -> not (p x)) xs

(* If [xss] is a matrix (a sequence of rows), then [peel xss] is a pair of
   the first column (a sequence of elements) and of the remainder of the
   matrix (a sequence of shorter rows). These two sequences have the same
   length. The rows of the matrix [xss] are not required to have the same
   length. An empty row is ignored. *)

(* Because [peel] uses [unzip], its argument must be persistent. The same
   remark applies to [transpose], [diagonals], [product], etc. *)

let peel xss =
  unzip (filter_map uncons xss)

let rec transpose xss () =
  let heads, tails = peel xss in
  if is_empty heads then begin
    assert (is_empty tails);
    Nil
  end
  else
    Cons (heads, transpose tails)

(* The internal function [diagonals] takes an extra argument, [remainders],
   which contains the remainders of the rows that have already been
   discovered. *)

let rec diagonals remainders xss () =
  match xss() with
  | Cons (xs, xss) ->
      begin match xs() with
      | Cons (x, xs) ->
          (* We discover a new nonempty row [x :: xs]. Thus, the next diagonal
             is [x :: heads]: this diagonal begins with [x] and continues with
             the first element of every row in [remainders]. In the recursive
             call, the argument [remainders] is instantiated with [xs ::
             tails], which means that we have one more remaining row, [xs],
             and that we keep the tails of the pre-existing remaining rows. *)
          let heads, tails = peel remainders in
          Cons (cons x heads, diagonals (cons xs tails) xss)
      | Nil ->
          (* We discover a new empty row. In this case, the new diagonal is
             just [heads], and [remainders] is instantiated with just [tails],
             as we do not have one more remaining row. *)
          let heads, tails = peel remainders in
          Cons (heads, diagonals tails xss)
      end
  | Nil ->
      (* There are no more rows to be discovered. There remains to exhaust
         the remaining rows. *)
      transpose remainders ()

(* If [xss] is a matrix (a sequence of rows), then [diagonals xss] is
   the sequence of its diagonals.

   The first diagonal contains just the first element of the
   first row. The second diagonal contains the first element of the
   second row and the second element of the first row; and so on.
   This kind of diagonal is in fact sometimes known as an antidiagonal.

   - Every diagonal is a finite sequence.
   - The rows of the matrix [xss] are not required to have the same length.
   - The matrix [xss] is not required to be finite (in either direction).
   - The matrix [xss] must be persistent. *)

let diagonals xss =
  diagonals empty xss

let map_product f xs ys =
  concat (diagonals (
    map (fun x ->
      map (fun y ->
        f x y
      ) ys
    ) xs
  ))

let product xs ys =
  map_product (fun x y -> (x, y)) xs ys

let of_dispenser it =
  let rec c () =
    match it() with
    | None ->
        Nil
    | Some x ->
        Cons (x, c)
  in
  c

let to_dispenser xs =
  let s = ref xs in
  fun () ->
    match (!s)() with
    | Nil ->
        None
    | Cons (x, xs) ->
        s := xs;
        Some x



let rec ints i () =
  Cons (i, ints (i + 1))