/
list.opa
1492 lines (1321 loc) · 44.4 KB
/
list.opa
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
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright © 2011 MLstate
This file is part of OPA.
OPA is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License, version 3, as published by
the Free Software Foundation.
OPA is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
more details.
You should have received a copy of the GNU Affero General Public License
along with OPA. If not, see <http://www.gnu.org/licenses/>.
*/
/*
@authors ?
**/
/**
* Lists and utilities to manipulate them.
*
* @author David Rajchenbach-Teller 2010 (review, clean-up and documentation)
*/
/**
* {1 Types defined in this module}
*/
/**
* The type of lists
* @param 'a The type of list elements
*
* {[{nil}} The empty list. As a syntactic shortcut, you can also write [[]].
* {[{ hd ; tl }} A list with at least one element.
* You can write equivalently [[1,2,3]] or
* [ {hd = 1 ; tl = {hd = 2 ; tl = {hd = 3 ; tl = {nil} } } } ]
**/
@opacapi
type list('a) =
{ nil }
/ { hd : 'a ; tl : list('a) }
/**
* {1 About this module}
*
* This module defines lists (also known as "linked lists"), an immutable data structure meant
* to contain finite or infinite sets of elements of the same type.
*
*
* {1 Where should I start?}
*
* To create a list containing elements 1, 2 and 3, the easiest is to write [[1,2,3]].
* The empty list is [[]]
* Once you have a list, typically, there may be a few things you wish to do with it:
*
* {2 Transforming lists}
*
* Do you have a list of numbers you wish to double? Try {!List.map}. Or perhaps you only wish to keep
* odd numbers? Look at {!List.filter}. Or perhaps you wish to keep this in odd positions? Look at
* {!List.filteri}.
*
*
* {2 Collecting list data}
*
* Do you wish to sum all the elements of a list? Try {!List.reduce}. Or perhaps you only wish to find
* the first even number? Try {!List.find}. Or perhaps you wish to compute its length? Try {!List.length}.
*
* {2 Sorting a list}
*
* To sort a list, use {!List.sort}. This function can adapt to your sorting criteria.
*
* {1 Limitations of this module}
*
* {1 What if I need more?}
*
* This module contains numerous other functions, including the all-powerful {!List.foldi}, which will
* let you apply arbitrary collections/transformations/loops based on the contents of a list.
*
* Lists are immutable, as are all base data structures in OPA -- this lets the compiler optimize numerous
* operations, including concurrency and database access. If you need mutability, you should consider wrapping
* your list in a {!Session}.
*
* List provide linear access time, i.e. don't use them if you frequently need to add data at the end
* or if you frequently need to access the [n]th element. For this purpose, you should rather use module
* [Array].
*/
List = {{
/**
* {1 Constructors}
**/
/**
* The empty list
*
* Provided for compatibility with other collections.
*/
empty = { nil } : list('a)
/**
* An alias for the empty list
*/
nil = empty : list('a)
/**
* Add an element at the start of a list
*
* [List.cons(e,l)] returns the list whose first element is [e] and in which the rest of the list is [l]
* You may also use the syntactic shorthands [[ e | l ]]
*
* You can combine several call to [cons] for creating a list with more elements,
* [ List.cons(0, List.cons(1, tl)) ] is equivalent to [[ 0, 1 | tl ]]
**/
cons(e:'a, l:list('a) ) = { hd = e ; tl = l } : list('a)
/**
* An alias for {!List.cons}
*
* Provided for compatibility with other collections.
*/
add = cons
/**
* A add in a list ordered by a function of comparison.
* Not tail rec, used for small list only
* in this case, this is more efficient than a Set.
**/
add_uniq(cmp: ('a, 'a -> Order.ordering), a, list) =
rec aux(list) =
match list with
| [] -> [a]
| [hd | tl] ->
match cmp(a, hd) with
| {eq} -> list
| {lt} -> [a | list]
| {gt} -> [ hd | aux(tl) ]
end
aux(list)
/**
* As {!List.cons}: adding an element at the head of a list.
**/
`+>` = cons
/**
* Create a list of [n] elements from a function.
*
* @param f A function, which will provide the contents of the list.
* @param n The size of the result. If 0 or less, the result is empty.
*
* This function produces [[f(0), f(1), ... , f(n - 1)]].
*
* Note: This function does not guarantee in which order [f(0)], [f(1)], etc.
* are called, so you should not use it if the order is important for the
* behavior of your program. In such a case, use {!List.init_stable} (or {!List.rev_init}).
*/
init(f: int -> 'a, n: int) =
rec aux(i,acc) =
if i < 0 then acc else aux(i - 1, cons(f(i), acc))
aux(n-1,[]) : list('a)
/**
* A variant on {!List.init}.
* Slower but guarantees order of function calls.
**/
init_stable(f:int -> 'a, n: int) = (rev_init(f,n) |> rev) : list('a)
/**
* As {!List.init} but in the reverse order.
**/
rev_init(f: int -> 'a, n: int) =
rec aux(i,acc) =
if i == n then acc else aux(i+1, cons( f(i) , acc))
aux(0,[]): list('a)
/**
* [List.iterate(f, x, n)] builds [x, f(x), f(f(x)), ..., f(...f(x))] of length [n].
* (so the last element of the list has [n - 1] applications of [f])
*/
iterate(f: 'a -> 'a, init: 'a, n: int) =
rec aux(i, x, l) =
if i <= 0 then (i, x, l) else aux(i - 1, f(x), cons(x, l))
(_, _, res) = aux(n, init, [])
rev(res) : list('a)
/**
* Concatenate two lists.
*
* Performance note: if you have a list you often need to extend at the end, rather than {!List.append},
* you should consider maintaining a list of lists, which will only be flattened once
* using {!List.flatten}.
*
* @param l1 The beginning.
* @param l2 The end.
*/
append( l1: list('a), l2: list('a)) =
match l2
[] -> l1
_ -> rev_append(rev(l1), l2) : list('a)
/**
* {2 Access functions}
**/
/**
* Determine if a list is empty.
*
* @return [{true}] if the list is empty, [{false}] otherwise.
*/
is_empty(l) =
match l with
| [] -> true
| _ -> false
/**
* Compute the length of a list.
*
* Performance note: if you only need to check whether a list is empty, you should rather use
* {!List.is_empty}, which is much faster than {!List.length}, in particular when your list is stored in
* the database.
*
* @return The number of elements in the list, which is [0] if the list is [{nil}] or a strictly
* positive number otherwise..
*/
length(l) =
rec aux( len, l ) =
match l with
| [] -> len
| [_ | tl] -> aux(succ(len), tl)
aux(0,l): int
/**
* Check that the list has the given length
*
* More efficient that computing the length of the list and then comparing
* against the desired length, because this function returns false earlier
* if the list is very long
*/
check_length(l:list,n:int) : bool =
if n == 0 then
match l with
| [] -> true
| _ -> false
else
match l with
| [] -> false
| [_ | t] -> check_length(t,n-1)
/**
* Get the [nth] element of a list.
*
* Performance note: if you are looping through a list, you should rather use the looping functions,
* which are much faster than calling [get(0,l)], [get(1,l)], ... [get(n,l)].
*
* @param n The index of an element of the list. The first element of the list is numbered [0].
* @return [{none}] if the list contains less than [n+1] elements or if [n] < 0. Otherwise [{some = x}], where [x]
* is the [nth] element of the list.
*/
get( n:int, l: list('a)): option('a) =
if Int.equals(Int.compare_raw(n, 0), -1) then none else
match l : list with
| [] -> none
| [hd | tl ] -> if Int.equals(n, 0) then some(hd) else get(n - 1, tl)
/**
* Get and remove the [nth] element of a list.
*
* @param n The index of an element of the list.
* @param l A list. If it contains less than [n+1] elements, the result will be [{none}],
* @return [({none}, l)] if the list contains less than [n+1] elements or if [n] < 0. Otherwise,
* [({some = x}, r)], where [x] is the [nth] element of the list and [r] is the list obtained by
* removing the first occurrence of [x] from [l].
*/
extract(n:int, l:list('a)) = extract_pi((j,_ -> n == j),l): (option('a), list('a))
/**
* {2 Loops}
*/
/**
* {3 Transforming lists}
*/
/**
* Transform a list by applying a function to each element.
*
* [map(f,[x1, x2, x3...])] will return [f(x1), f(x2), f(x3), ...]
*
* @param f A transformation function.
* @param l A list, possibly empty.
* @return A new list with the same size as [l].
*/
map(f:'a -> 'b, l: list('a)) =
rec aux(f, l, c) =
match Int.compare(c, 100) with // tail rec if list size > 100
| {gt} -> rev_map(f, l) |> rev
| _ ->
match l : list with
| [] -> empty
| [hd | tl] -> add( f(hd), aux(f, tl, c+1) )
end
end
aux(f, l, 0): list('b)
/**
* As [map], but the transformation function is informed of the current position in the list.
*/
mapi(f:int, 'a -> 'b, l: list('a)) =
rev_mapi(f, l) |> rev
/**
* Transform a list by removing some elements.
*
* @param f A function deciding which items to keep. Wherever [f] returns [{true}], the
* item is kept, otherwise it is discarded.
* @param l The original list.
* @return A list, possibly empty, containing only the elements of [l] for which [f] has
* returned [{true}].
*/
filter(f: 'a -> bool, l: list('a)) =
filteri( _i,x -> f(x), l) : list('a)
/**
* As [filter] but the function is informed of the position of the current element.
*/
filteri(f: int, 'a -> bool, l: list('a)) =
rec aux(list, pos, accu) =
match (list : list) with
| [hd | tl ] -> aux(tl, (pos+1), if f(pos,hd) then cons(hd, accu) else accu)
| [] -> rev(accu)
aux(l, 0, []): list('a)
/**
* Transform a list, removing some elements, changing others.
*
* This function lets you loop through a list and transform it into a different list.
* Transformations combine the power of [map] (applying a function to an element to
* obtain a distinct element) and the power of [filter] (discarding elements that do
* not fit some criterium).
*
* @param f A function returning for each item [{some = y}] if [y] should be added to
* the destination list or [{none}] otherwise.
* @param l A list to visit.
* @return A list, containing the non-[{null}] images of items of [l] by [f], in the
* same order.
*/
filter_map(f:'a -> option('b), l:list('a)) =
rec aux(f, l, c) =
if c > 100 then rev_filter_map(f, l) |> rev
else
match l : list with
| [] -> empty
| [hd | tl] ->
match f(hd) with
| { none } -> aux(f, tl, c+1)
| { ~some } -> add(some, aux(f, tl, c+1))
end
aux(f, l, 0): list('b)
/**
* {3 Side-effects}
*/
/**
* Apply a function to all the elements of a list.
*
* By opposition to [fold], [map], [filter] and their variants, this function is meant to
* perform side-effects (e.g. displaying information or sending data to a session) rather
* than extracting some information or building a new data structure.
*
* Example: [iter(jlog("{_}"), [1,2,3,4,5])] will print the numbers
* between 1 and 5.
*
* See also: [iteri] behaves as [iter] but also informs the function of the current
* position in the list.
*
* @param f A function to apply to each element of the list. As a sanity check, this function must
* return [void].
* @param l A list, possibly empty.
*/
iter(f: 'a -> void, l: list('a)):void =
match l:list with
| [hd | tl] -> do f(hd):void; iter(f,tl)
| [] -> void : void
/**
* As [iter] but informs the function of the current position in the list.
*
* [iteri(f,[x0,x1,x2...])] will execute [f(0,x0)], [f(0,x1)], ...
*
* @param f A function to apply to each element of the list, along with its position.
* @param l A list, possibly empty.
*/
iteri(f: int, 'a -> void, l: list('a)) =
rec aux(i,l) = match l:list with
| [hd | tl] -> do f(i,hd):void; aux(i+1,tl)
| [] -> void
aux(0,l)
/**
* {3 Collecting data}
*/
/**
* Loop through a list, collecting data from the list.
*
* This function implements a general-purpose loop on lists.
* It is extremely powerful and could be used
* to reimplement most of the functions in this module.
*
* [fold(f, [x0, x1, x2, ...], init)] will compute
* [f(... f(x2, f(x1, f(x0, init))) ...)]
*
* Example: the following expression computes
* the sum of all elements of a list [fold(_+_, l, 0)].
*
* Example: the following expression computes
* the length of a list [fold((_,i -> i+1), l, 0)]
*
* @param f A function invoked at each element of the
* list to update the data.
* @param l The list to visit.
* @param The initial data. If the list is empty, this
* will also be the result.
*/
fold(f:'item, 'acc -> 'acc, l: list('item), init:'acc ): 'acc =
// do Log.notice("Fold", l)
match l : list with
| [] -> init
| [hd | tl] -> fold(f, tl, f(hd,init)): 'acc
/**
* As {!List.fold} but the function is informed of the position of
* the current element.
*/
foldi(f:int, 'item, 'acc -> 'acc, l: list('item), init:'acc ) =
rec aux(l: list, accu, ct: int) =
match l with
| { ~hd ~tl } -> aux(tl, f(ct,hd,accu), ct+1)
| _ -> accu
aux(l, init, 0): 'acc
/**
* As {!List.fold} but starting from the end.
*/
fold_backwards(f:'item, 'acc -> 'acc, l: list('item), init:'acc ) =
rev(l) |> fold( f, _, init )
/**
* As {!List.foldi} but starting from the end.
*/
foldi_backwards(f:int, 'item, 'acc -> 'acc, l: list('item), init:'acc ) =
rev(l) |> foldi( f, _, init )
/**
* {2 Other transformations}
*/
/**
* Split a list in two.
*
* This function takes a decision criterium list and returns two list: one with all
* the elements that match the criterium and one with all the elements that don't.
*
* Example:
*
* [
* is_even(x) = x mod 2 == 0
* partition(is_even, [1,2,3,4,5,6,7,8])
* ] returns [([2,4,6,8], [1,3,5,7])]
*
* @param f A function deciding in which lists elements will end. Items for which
* [f] returns [{true}] will be placed in a first list, while items for which
* [f] returns [{false}] will be placed in a second list.
* @param l The original list.
*
* @return A pair of lists [(left, right)], where [left] contains all the elements
* [x] of [l] such that [f(x)] returns [{true}] and [right] contains the other
* elements. The order of elements is preserved.
*/
partition(f: 'a -> bool, l: list('a)) =
partitioni(_i,x -> f(x), l)
/**
* As {!List.partition} but the function is informed of the position of the current element.
*/
partitioni(f: int, 'a -> bool, l: list('a)) =
rec aux(l, pos, acc_left, acc_right) = match l: list with
| { ~hd ~tl } -> if f(pos, hd)
then aux(tl, (pos+1), cons(hd, acc_left), acc_right)
else aux(tl, (pos+1), acc_left, cons(hd, acc_right))
| _ -> (rev(acc_left),rev(acc_right))
aux(l, 0, [], []) : (list('a), list('a))
/**
* {2 Searching}
*/
/**
* Search for an element in a list.
*
* This function searches the first occurrence of an element in a list and returns
* its index.
*
* @param x The element to find.
* @param l The list in which to find.
* @return [{none}] if the element doesn't appear in the list or [{some = i}]
* if the first occurrence of [x] appears at index [i].
*/
index(x:'a, l: list('a)) = index_p(x == _,l) : option(int)
/**
* Search for an element in a list.
*
* This function searches the first occurrence of any element matching a given predicate
* and returns its index.
*
* @param p A function deciding whether the element is the one we are looking for.
* @param l The list in which to find.
* @return [{none}] if no acceptable element doesn't appear in the list or [{some = i}]
* if the first occurrence of [x] appears at index [i].
*/
index_p(p:'a -> bool, l: list('a)) =
rec aux(i,l) =
match l with
| [] -> none
| [hd | tl] -> if p(hd) then some(i) else aux(i+1,tl)
aux(0,l): option(int)
/**
* As [index_p] but returns the element itself, not its index.
*/
find(f:'a -> bool , l:list('a)) =
match l with
| [] -> none
| [hd | tl] -> if f(hd) then some(hd) else find(f, tl) : option('a)
/**
* As [index], but returns [true] if the element can be found, not its index.
*/
mem(x,l) =
exists(_ == x, l)
/**
* Check whether all elements of an index match a given condition.
*
* @param f The condition.
* @param l A list, possibly empty.
* @return [{true}] if [f] returns [{true}] for all elements of [l] (in particular if [l] is empty), [{false}] otherwise.
*/
for_all(f, l) =
match l with
| [] -> true
| [hd | tl] -> f(hd) && for_all(f, tl)
/**
* Check whether all pair of corresponding elements of the pair of list match a given condition
* @param f The condition
* @param l1 A list
* @param l2 An other, with a possibly different length
* @return {result={true}} if the predicate is satisfied everywhere and the lists have the same length
* {result={false}} if the predicate failed before the end of the shorter list
* {different_length=reason} if the predicate succeeded until the end of the shorter list
* (reason is either {longest_first} or {longest_second})
* Note that if the lists have different lengths but the predicate fails before the end
* of one of the list, then you will get {result=false} and not {different_length=...}
*/
for_all2(f, l1, l2) =
match l1
| [] ->
match l2 with
| [] -> {result=true}
| [_|_] -> {different_length={longest_second}}
end
| [h1|l1] ->
match l2 with
| [] -> {different_length={longest_first}}
| [h2|l2] ->
if f(h1,h2) then for_all2(f, l1, l2) else {result=false}
/**
* Check whether at least one element of an index matches a given condition.
*
* @param f The condition.
* @param l A list, possibly empty.
* @return [{true}] if [f] returns [{true}] for at least one element of [l], [{false}] otherwise (in particular if [l] is empty).
*/
exists(f, l) =
match l with
| [] -> false
| [hd | tl] -> f(hd) || exists(f, tl)
/**
* Find the first element of a list verifying some condition and return it after treatment.
*
* This function is equivalent to a composition of [find] and [Option.map].
*
* @param f A decision function returning [{none}] if the current item is not the one being
* searched, or [{some = x}] if the current item is the one being searched and the result should
* be [x].
* @param l A list, possibly empty.
* @return if [f] produced at least one result other than [{none}] on elements of [l], this result
* otherwise [{none}].
*/
find_map(f:'a -> option('b), l:list('a)) =
match l with
| [] -> none
| [hd | tl] -> (match f(hd) with
| {some=_} as res -> res
| _ -> find_map(f, tl)): option('b)
/**
* {2 Removing things}
*/
/**
* Separate a list in two.
*
* @param l The list to separate.
* @param n The number of elements to put in the first list.
* @return A pair [(beginning, end)] such that [append(beginning,end) == l]
* If [l] has [n] elements or more, [beginning] contains the [n] first elements
* of [l], otherwise [beginning] is [l].
*/
split_at(l: list('a), n: int) =
if n<=0 then (empty, l)
else
rec aux(debut, fin, n) =
if n==0 then (rev(debut) , fin)
else match (fin : list)
| {~hd ~tl} -> aux(cons(hd,debut),tl,n-1)
| _ -> (rev(debut) , fin)
aux([],l,n): (list('a), list('a))
/**
* Separate a list in two
*
* @param l The list to separate.
* @param n The number of elements to put in the first list.
* If [l] has [n] elements or more, the output is identical to split_at
* otherwise, returns [{none}]
*/
split_at_opt(l:list('a), n:int) : option((list('a), list('a))) =
if n < 0 then {none} else
rec aux(acc,l,n) =
if n == 0 then {some = (rev(acc),l)} else
match l with
| [] -> /* the list is shorter than n */ {none}
| [h|t] -> aux([h|acc],t,n-1)
aux([],l,n)
/**
* Separate a list in two
*
* @param l The list to separate.
* @param min The minimum number of elements to put in the first list.
* @param max The maximum number of elements to put in the first list.
* if [min] > [max], return [{none}]
* If [l] has less than [min] element, return [{none}]
* If [l] has more than [max] element, return [split_at_opt(l,max)]
* If [l] has between [min] and [max], returns [{some=(l,[])}]
*/
split_between(l:list('a), min:int, max:int) : option((list('a),list('a))) =
if max < 0 then {none} else
rec aux(acc,l,min,max) =
if max == 0 then
if min <= 0 then
{some = (rev(acc),l)}
else
{none}
else
match l with
| [] -> /* the list is shorted than n */ {none}
| [h|t] -> aux([h|acc],t,min-1,max-1)
aux([],l,min,max)
/**
* Separate a list in two halves.
*
* @param l A list, possibly empty.
* @return A pair [(beginning, end)] such that [(append(beginning, end) == l)] and
* and such that either [beginning] and [end] have the same length or the length
* of [end] is equal to the length of [beginning] + 1.
*/
split_middle(l: list('a)) = split_at(l, length(l)/2): (list('a), list('a))
/**
* Remove the [n] first elements of a list.
*
* @param n The number of elements to remove. If n <= 0, the list is return unchanged.
* @param l The original list. If the list contains at most [n] elements, the empty list is returned.
*/
drop(n: int, l: list) =
if n <= 0 then l
else
match l with
| [] -> []
| [_ | tl] -> drop(n - 1, tl)
/**
* Keep the [n] first elements of a list.
*
* @param n The number of elements to keep. If n <= 0, the result is [empty].
* @param l The original list. If it contains less than [n] elements, the original list is returned.
*/
take(n:int, li:list) =
rec aux(i,rest,acc) = match rest : list with
| [] -> li /*List is shorter than [n], take returns the whole list.*/
| [hd | tl] -> if i <= 0 then rev(acc)
else aux(i - 1, tl, cons(hd, acc))
aux(n,li,[])
/**
* Extract an element from a list.
*
* @param f A decision function returning [{true}] if the item encountered is the item found, [{false}] otherwise.
* @param l A list in which to look, possibly empty.
* @return Either [({none}, l)] if no matching could be found or [({some = x}, rest)] if an element [x] could be found
* and [rest] is equal to [l] minus the first occurrence of [x].
*/
extract_p(f:'a -> bool, l:list('a)) =
rec aux(r, (acc : list)) =
match r : list with
| [] -> (none,l)
| [hd | tl] -> if f(hd) then (some(hd),rev_append(acc,tl)) else aux(tl,hd+>acc)
aux(l,[]): (option('a), list('a))
/**
* As {!List.extract_p} but the function is informed of the position of the current element.
*/
extract_pi(f, l) =
rec aux(r, (acc : list), i) =
match r : list with
| [] -> (none,l)
| [hd | tl] -> if f(i,hd) then (some(hd),rev_append(acc,tl)) else aux(tl,hd+>acc,i+1)
aux(l,[],0)
/**
* As {!List.extract_p} but only returns the resulting list.
*/
remove_p(p, l) = extract_p(p, l).f2
/**
* As {!List.extract_pi} but only returns the resulting list.
*/
remove_pi(p, l) = extract_pi(p, l).f2
/**
* As {!List.extract} but only returns the resulting list.
*/
remove_at(i,l) = extract(i,l).f2
/**
* Remove the first occurrence of an element in a list.
*
* @return the list unchanged if the element doesn't appear in the list, otherwise the list
* minus the first occurrence of [x]
*/
remove(x: 'a, l:list('a)) = remove_p(_ == x, l): list('a)
/**
* Remove duplicates from a list.
*
* @return a list containing all the elements of [l] exactly once. Note that the elements of
* this list may appear in a different order than in [l].
*/
unique_list_of(l:list('a)) =
unique_list_of_sorted(sort(l)): list('a)
/**
* {2 Looping on two lists at once}
*/
map2_gen_aux(f:'a,'b -> 'c, acc:list('c), l1:list('a), l2:list('b)) : {result:list('c)} / {different_length:list('c)} =
match l1 with
| [] ->
match l2 with
| [] -> {result=rev(acc)}
| [_|_] -> {different_length=rev(acc)}
end
| [h1|t1] ->
match l2 with
| [] -> {different_length=rev(acc)}
| [h2|t2] -> map2_gen_aux(f, [f(h1,h2)|acc], t1, t2)
end
/**
* Transforms two lists by applying a function to each pair of elements
* @return a sum {result=l} when the list have the same length
* or {different_length=l} when list have different with the result so far
*/
map2_gen(f, l1, l2) =
map2_gen_aux(f, [], l1, l2)
/**
* Transform two lists by applying a function to each pair of elements at the same position.
*
* [map(f,[x1, x2, x3...],[y1, y2, y3, ...])] will return [f(x1,y1), f(x2,y2), f(x3,y3), ...]
*
* @param f A transformation function.
* @param l1 A list, possibly empty.
* @param l2 A list, possibly empty.
* @return A new list with the same size as the smallest of [l1], [l2].
*/
map2(f: 'a, 'b -> 'c, l1: list('a), l2: list('b)) =
match map2_gen(f, l1, l2) with
| {result=res} -> res
| {different_length=res} -> res
/**
* Combine two lists into a list of pairs.
*
* [zip([x1, x2, x3, ...], [y1, y2, y3, ...])] will return [(x1, y1), (x2, y2), (x3, y3)...]
* @return A new list with the same size as the smallest of [l1], [l2].
*/
zip(l1: list('a), l2:list('b)) = map2(x, y -> (x, y), l1, l2) : list(('a,'b))
/**
* Separate a lists of pairs into two lists.
*/
unzip(l: list(('a, 'b))) = fold_backwards( (v1,v2),(acc1,acc2)->(add(v1,acc1),add(v2,acc2)) , l, ([],[]) ) : (list('a), list('b))
compare(cmp:'a,'a -> Order.comparison,l1:list('a),l2:list('a)):Order.comparison =
match l1 with
| [] ->
match l2 with
| [] -> {eq}
| _ -> {gt}
end
| [h1|l1] ->
match l2 with
| [] -> {lt}
| [h2|l2] ->
match cmp(h1, h2) with
| {eq} -> compare(cmp,l1,l2)
| c -> c
ordering(using:order('a, 'b),l1:list('a),l2:list('a)):Order.ordering =
rec f(l1, l2) =
match l1 with
| [] ->
match l2 with
| [] -> {eq}
| _ -> {gt}
end
| [h1|l1] ->
match l2 with
| [] -> {lt}
| [h2|l2] ->
match Order.compare(h1, h2, using) with
| {eq} -> f(l1,l2)
| c -> c
f(l1, l2)
make_order(using:order('a, 'b)):order(list('a), 'b) =
Order.make(ordering(using, _, _))
/**
* {2 Changing order}
*/
/**
* Revert a list.
*
* @param l A list, possibly empty.
* @return The same list, reversed.
*/
rev(l: list('a)) = rev_append(l,empty): list('a)
/**
* {2 Association lists}
*
* The following functions work on lists of pairs of elements, typically
* used as dictionaries (e.g. a key and a value). By definition, association
* lists behave as if adding a new element with a given key masks all previous
* elements with the same key.
*
* Note that module [Map] provides dictionaries which are generally much
* faster than association lists. Use association lists if your dictionaries
* are small or if you wish to guarantee that the order of elements does not
* change.
*/
/**
* Find the value associated to a key.
*
* @param k A key.
* @param l An association list.
* @return [{none}] if the list did not contain any value associated to
* this key, otherwise [{some = v}], where [v] is the value associated to [k].
*/
assoc(k:'a, l:list(('a,'b)) ) = assoc_gen(eq, k, l): option('b)
/**
* As [assoc], but with control on the comparison function.
*
* Use this function rather than [assoc] if you wish to use a special-purpose
* comparison function, e.g. to compare texts without case.
*
* @param equals A comparison function.
* @param k A key.
* @param l An association list.
* @return [{none}] if the list did not contain any value associated to
* this key, otherwise [{some = v}], where [v] is the value associated to [k].
*/
assoc_gen(equals: 'a, 'a -> bool, k:'a, l:list(('a,'b)) ) =
rec aux(tl) = match tl with
| [] -> none
| [(key, val) | tl] ->
if equals(key,k) then some(val)
else aux(tl): option('b)
aux(l)
//FRS says: what follows is not about association lists
/**
* Insert an item in a list at a given position.
*
* @param item The item to insert in the list.
* @param index The position at which to insert.
* @param list The list in which to insert. If [index < 0] or [index >= length(list)],
* the list is returned unchanged.
*/
insert_at(item:'a, index:int, list: list('a)) =
if index < 0 then list
else rec aux(i, (acc : list), l) =
if i == 0 then rev_append(acc, cons(item, l))
else match l : list
| [] -> list//List too short, don't insert
| [hd | tl] -> aux(i - 1, cons(hd, acc), tl) : list('a)
aux(index, [], list)
/**
* Transform a list or give up.
*
* This function is a variant on [filter_map] which returns [{none}] if any of the
* calls to the decision function returns [{none}].
*
* @param f A function deciding whether to stop or how to transform the current item.
* If [f] returns [{none}], the result of [map_while_opt] is [{none}]. Otherwise, put
* the result of [f] into the resulting list.
* @param l A list, possibly empty.
* @return [{none}] if any of the calls to [f] returned [{none}]. Otherwise, [{some = l}],
* where [l] is the list obtained from the successive [{some}] results of calls to [f].
*/
map_while_opt(f:'a -> option('b), l:list('a)) =//TODO: This function will become useless with lazy lists.
rec aux((acc : list), (li : list)) = match li
| [] -> some(rev(acc))
| [hd | tl] -> match f(hd)
| {none} -> {none}
| {some = x} -> aux(cons(x,acc), tl)
end
end
aux([], l) : option(list('b))
/**
* {2 Special-purpose optimizations}
*
* The following functions are specialized counterparts
* to more general functions, optimized for some specific
* cases.
*
* These functions are typically useful if you do not care
* about the order of elements in the list or if you know
* exactly when and how you intend to revert the order of
* such elements.
*/
/**
* Revert a list and append it to another one.
*
* Performance note: This function is provided solely for performance reasons, as it is much
* faster than performing either [append(l1, l2)] or [append(rev(l1), l2)].
*