-
Notifications
You must be signed in to change notification settings - Fork 3
/
AllDictList.elm
1321 lines (1030 loc) · 40.2 KB
/
AllDictList.elm
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
module AllDictList
exposing
( AllDictList
-- originally from `AllDict`
, empty
, eq
, fullEq
, getOrd
, singleton
, insert
, update
, isEmpty
, get
, remove
, member
, size
, filter
, partition
, foldl
, foldr
, map
, union
, intersect
, diff
, merge
, keys
, values
, toList
, fromList
-- core `List`
, cons
, head
, tail
, indexedMap
, filterMap
, length
, reverse
, all
, any
, append
, concat
, sum
, product
, maximum
, minimum
, take
, drop
, sort
, sortBy
, sortWith
-- list-oriented
, getAt
, getKeyAt
, indexOfKey
, insertAfter
, insertBefore
, next
, previous
, reorder
, RelativePosition(..)
, relativePosition
, insertRelativeTo
, atRelativePosition
-- JSON
, decodeObject
, decodeWithKeys
, decodeKeysAndValues
, decodeArray
, decodeArray2
-- Conversion
, toAllDict
, toDict
, fromAllDict
, fromDict
-- Dict.Extra
, groupBy
, fromListBy
, removeWhen
, removeMany
, keepOnly
, mapKeys
)
{-| Have you ever wanted an `AllDict`, but you need to maintain an arbitrary
ordering of keys? Or, a `List`, but you want to efficiently lookup values
by a key? With `AllDictList`, now you can!
`AllDictList` implements the full API for `AllDict` (and should be a drop-in
replacement for it). However, instead of ordering things from lowest
key to highest key, it allows for an arbitrary ordering.
We also implement most of the API for `List`. However, the API is not
identical, since we need to account for both keys and values.
An alternative would be to maintain your own "association list" -- that is,
a `List (k, v)` instead of an `AllDictList k v`. You can move back and forth
between an association list and a dictionary via `toList` and `fromList`.
# AllDictList
@docs AllDictList, RelativePosition
@docs eq, fullEq, getOrd
# Build
Functions which create or update a dictionary.
@docs empty, singleton, insert, update, remove
@docs take, drop
@docs removeWhen, removeMany, keepOnly
@docs cons, insertAfter, insertBefore, insertRelativeTo
# Combine
Functions which combine two `AllDictLists`.
@docs append, concat
@docs union, intersect, diff, merge
# Query
Functions which get information about a dictionary.
@docs isEmpty, size, length
@docs all, any
@docs sum, product, maximum, minimum
# Elements
Functions that pick out an element of a dictionary,
or provide information about an element.
@docs member, get, getAt, getKeyAt
@docs indexOfKey, relativePosition, atRelativePosition
@docs head, tail
@docs next, previous
# Transform
Functions that transform a dictionary
@docs map, mapKeys, foldl, foldr, filter, partition
@docs indexedMap, filterMap, reverse, reorder
@docs sort, sortBy, sortWith
# Convert
Functions that convert between a dictionary and a related type.
@docs keys, values, toList, fromList, fromListBy, groupBy
@docs toAllDict, fromAllDict
@docs toDict, fromDict
# JSON
Functions that help to decode a dictionary.
@docs decodeObject, decodeArray, decodeArray2, decodeWithKeys, decodeKeysAndValues
-}
import AllDict exposing (AllDict)
import Dict exposing (Dict)
import Json.Decode exposing (Decoder, keyValuePairs, value, decodeValue)
import Json.Decode as Json18
import List.Extra
import Maybe as Maybe18
import Set exposing (Set)
import Tuple exposing (first, second)
{-| An `AllDict` that maintains an arbitrary ordering of keys (rather than sorting
them, as a normal `AllDict` does). Or, a `List` that permits efficient lookup of
values by a key. You can look at it either way.
-}
type AllDictList k v comparable
= AllDictList (AllDict k v comparable) (List k)
{- I considered something like this instead:
type AllDictList k v comparable = AllDictList (AllDict k v comparable) (List (k, v))
This would speed up some things, because our `List` would have the values
as well -- we wouldn't have to look them up in the `AllDict` when doing
list-oriented things. However, it would slow down other things, because
we'd have to modify the list in cases where only the value was changing,
not the key. So, it's something we could reconsider depending on
desired performance characteristics.
Another performance issue down the road would be whether to use `Array`
for the internal implementation rather than `List`. I didn't use `Array`
originally because it has some notable bugs, but that is likely to change
in Elm 0.19.
-}
{-| Describes the position of a key in relation to another key (before or after
it), rather than using an index.
-}
type RelativePosition k
= BeforeKey k
| AfterKey k
-------
-- JSON
-------
{-| Turn any object into a dictionary of key-value pairs, including inherited
enumerable properties. Fails if *any* value can't be decoded with the given
decoder.
Unfortunately, it is not possible to preserve the apparent order of the keys in
the JSON, because the keys in Javascript objects are fundamentally un-ordered.
Thus, you will typically need to have at least your keys in an array in the JSON,
and use `decodeWithKeys`, `decodeArray` or `decodeArray2`.
-}
decodeObject : Decoder a -> Decoder (AllDictList String a String)
decodeObject decoder =
Json.Decode.map (fromList identity) (keyValuePairs decoder)
{-| This function produces a decoder you can use if you can decode a list of your keys,
and given a key, you can produce a decoder for the corresponding value. The
order within the resulting dictionary will be the order of your list of keys.
-}
decodeWithKeys : (k -> comparable) -> List k -> (k -> Decoder v) -> Decoder (AllDictList k v comparable)
decodeWithKeys ord keys func =
let
go jsonValue key accum =
case ( accum, decodeValue (func key) jsonValue ) of
( Ok goodSoFar, Ok thisTime ) ->
-- If we've been successful so far, and OK this time, then accumulate
Ok <| insert key thisTime goodSoFar
( Ok goodSoFar, Err err ) ->
-- If we were OK until now, but this one erred, then the whole thing fails
Err err
( Err err, Ok _ ) ->
-- If we've already had an error, but this one is good, just keep the error
accum
( Err err1, Err err2 ) ->
-- If we had an error, and we have another one, combine them
Err <| err1 ++ "\n" ++ err2
in
value
|> Json18.andThen
(\jsonValue ->
case List.foldl (go jsonValue) (Ok (empty ord)) keys of
Ok result ->
Json.Decode.succeed result
Err err ->
Json.Decode.fail err
)
{-| Like `decodeWithKeys`, but you supply a decoder for the keys, rather than the keys themselves.
Note that the starting point for all decoders will be the same place, so you need to construct your
decoders in a way that makes that work.
-}
decodeKeysAndValues : (k -> comparable) -> Decoder (List k) -> (k -> Decoder v) -> Decoder (AllDictList k v comparable)
decodeKeysAndValues ord keyDecoder func =
keyDecoder
|> Json18.andThen (\keys -> decodeWithKeys ord keys func)
{-| Given a decoder for the value, and a way of turning the value into a key,
decode an array of values into a dictionary. The order within the dictionary
will be the order of the JSON array.
-}
decodeArray : (k -> comparable) -> (v -> k) -> Decoder v -> Decoder (AllDictList k v comparable)
decodeArray ord keyMapper valueDecoder =
Json.Decode.map
(List.map (\value -> ( keyMapper value, value )) >> (fromList ord))
(Json.Decode.list valueDecoder)
{-| Decodes a JSON array into the AllDictList. You supply two decoders. Given an element
of your JSON array, the first decoder should decode the key, and the second decoder
should decode the value.
-}
decodeArray2 : (k -> comparable) -> Decoder k -> Decoder v -> Decoder (AllDictList k v comparable)
decodeArray2 ord keyDecoder valueDecoder =
Json18.map2 (,) keyDecoder valueDecoder
|> Json.Decode.list
|> Json.Decode.map (fromList ord)
----------------------
-- From `List` in core
----------------------
{-| Insert a key-value pair at the front. Moves the key to the front if
it already exists.
-}
cons : k -> v -> AllDictList k v comparable -> AllDictList k v comparable
cons key value (AllDictList dict list) =
AllDictList
(AllDict.insert key value dict)
(key :: removeKey key dict list)
{-| Gets the first key with its value.
-}
head : AllDictList k v comparable -> Maybe ( k, v )
head (AllDictList dict list) =
List.head list
|> Maybe18.andThen (\key -> AllDict.get key dict |> Maybe.map (\value -> ( key, value )))
{-| Extract the rest of the dictionary, without the first key/value pair.
-}
tail : AllDictList k v comparable -> Maybe (AllDictList k v comparable)
tail (AllDictList dict list) =
case list of
first :: rest ->
Just <|
AllDictList (AllDict.remove first dict) rest
_ ->
Nothing
{-| Like `map` but the function is also given the index of each
element (starting at zero).
-}
indexedMap : (Int -> k -> v1 -> v2) -> AllDictList k v1 comparable -> AllDictList k v2 comparable
indexedMap func dictlist =
let
go key value ( index, AllDictList dict list ) =
( index + 1
, AllDictList
(AllDict.insert key (func index key value) dict)
(key :: list)
)
in
-- We need to foldl, because the first element should get the 0 index.
-- But we build up the resulting list with `::`, for efficiency, so
-- we reverse once at the end.
foldl go ( 0, emptyWithOrdFrom dictlist ) dictlist
|> second
|> reverse
{-| Apply a function that may succeed to all key-value pairs, but only keep
the successes.
-}
filterMap : (k -> v1 -> Maybe v2) -> AllDictList k v1 comparable -> AllDictList k v2 comparable
filterMap func dictlist =
let
go key value acc =
func key value
|> Maybe.map (\result -> cons key result acc)
|> Maybe.withDefault acc
in
foldr go (emptyWithOrdFrom dictlist) dictlist
{-| The number of key-value pairs in the dictionary.
-}
length : AllDictList k v comparable -> Int
length =
size
{-| Reverse the order of the key-value pairs.
-}
reverse : AllDictList k v comparable -> AllDictList k v comparable
reverse (AllDictList dict list) =
AllDictList dict (List.reverse list)
{-| Determine if all elements satisfy the predicate.
-}
all : (k -> v -> Bool) -> AllDictList k v comparable -> Bool
all func dictlist =
not (any (\key value -> not (func key value)) dictlist)
{-| Determine if any elements satisfy the predicate.
-}
any : (k -> v -> Bool) -> AllDictList k v comparable -> Bool
any func (AllDictList dict list) =
let
go innerList =
case innerList of
[] ->
False
first :: rest ->
if func first (unsafeGet first dict) then
True
else
go rest
in
go list
{-| Put two dictionaries together.
If keys collide, preference is given to the value from the second dictionary.
Also, the order of the keys in the second dictionary will be preserved at the
end of the result.
So, you could think of `append` as biased towards the second argument. The end
of the result should be equal to the second argument, both in value and key-order.
The front of the result will then be whatever is left from the first argument --
that is, those keys (and their values) that were not in the second argument.
For a similar function that is biased towards the first argument, see `union`.
-}
append : AllDictList k v comparable -> AllDictList k v comparable -> AllDictList k v comparable
append t1 t2 =
let
go key value acc =
-- We're right-favouring, so only act if the key is not already present
if member key acc then
acc
else
cons key value acc
in
foldr go t2 t1
{-| Concatenate a bunch of dictionaries into a single dictionary.
Works from left to right, applying `append` as it goes.
-}
concat : (k -> comparable) -> List (AllDictList k v comparable) -> AllDictList k v comparable
concat ord lists =
-- You might wonder why we need the `ord`, since we could get it from one
-- of the things we're combining. But, which one? They aren't necessarily
-- the same function. And, what if the list is empty? Then we don't have
-- one. So, we have to ask for one.
List.foldr append (empty ord) lists
{-| Get the sum of the values.
-}
sum : AllDictList k number comparable -> number
sum (AllDictList dict list) =
AllDict.foldl (always (+)) 0 dict
{-| Get the product of the values.
-}
product : AllDictList k number comparable -> number
product (AllDictList dict list) =
AllDict.foldl (always (*)) 1 dict
{-| Find the maximum value. Returns `Nothing` if empty.
-}
maximum : AllDictList k comparable1 comparable2 -> Maybe comparable1
maximum (AllDictList dict list) =
-- I considered having `maximum` and `minimum` return the key
-- as well, but there is a bit of a puzzle there. What would
-- one do when there are ties for the maximum value?
let
go _ value acc =
case acc of
Nothing ->
Just value
Just bestSoFar ->
Just <| max bestSoFar value
in
AllDict.foldl go Nothing dict
{-| Find the minimum value. Returns `Nothing` if empty.
-}
minimum : AllDictList k comparable1 comparable2 -> Maybe comparable1
minimum (AllDictList dict list) =
let
go _ value acc =
case acc of
Nothing ->
Just value
Just bestSoFar ->
Just <| min bestSoFar value
in
AllDict.foldl go Nothing dict
{-| Take the first *n* values.
-}
take : Int -> AllDictList k v comparable -> AllDictList k v comparable
take n (AllDictList dict list) =
let
newList =
List.take n list
newDict =
List.foldl go (AllDict.empty (AllDict.getOrd dict)) newList
go key =
AllDict.insert key (unsafeGet key dict)
in
AllDictList newDict newList
{-| Drop the first *n* values.
-}
drop : Int -> AllDictList k v comparable -> AllDictList k v comparable
drop n (AllDictList dict list) =
let
newList =
List.drop n list
newDict =
List.foldl go (AllDict.empty (AllDict.getOrd dict)) newList
go key =
AllDict.insert key (unsafeGet key dict)
in
AllDictList newDict newList
{-| Sort values from lowest to highest
-}
sort : AllDictList k comparable1 comparable2 -> AllDictList k comparable1 comparable2
sort ((AllDictList dict _) as dictList) =
toList dictList
|> List.sortBy second
|> List.map first
|> AllDictList dict
{-| Sort values by a derived property.
-}
sortBy : (v -> comparable1) -> AllDictList k v comparable2 -> AllDictList k v comparable2
sortBy func ((AllDictList dict _) as dictList) =
toList dictList
|> List.sortBy (func << second)
|> List.map first
|> AllDictList dict
{-| Sort values with a custom comparison function.
-}
sortWith : (v -> v -> Order) -> AllDictList k v comparable -> AllDictList k v comparable
sortWith func ((AllDictList dict _) as dictList) =
toList dictList
|> List.sortWith (\v1 v2 -> func (second v1) (second v2))
|> List.map first
|> AllDictList dict
----------------
-- List-oriented
----------------
{-| Given a key, what index does that key occupy (0-based) in the
order maintained by the dictionary?
-}
indexOfKey : k -> AllDictList k v comparable -> Maybe Int
indexOfKey key (AllDictList dict list) =
-- Can't just use `elemIndex` because that relies on `==`, which may be
-- unreliable ... need to use the `ord`.
let
ord =
AllDict.getOrd dict
target =
ord key
in
List.Extra.findIndex (\k -> ord k == target) list
{-| Given a key, get the key and value at the next position.
-}
next : k -> AllDictList k v comparable -> Maybe ( k, v )
next key dictlist =
indexOfKey key dictlist
|> Maybe18.andThen (\index -> getAt (index + 1) dictlist)
{-| Given a key, get the key and value at the previous position.
-}
previous : k -> AllDictList k v comparable -> Maybe ( k, v )
previous key dictlist =
indexOfKey key dictlist
|> Maybe18.andThen (\index -> getAt (index - 1) dictlist)
{-| Use the supplied keys to reorder the dictionary.
- Any keys that do not already exist in the dictionary will be ignored.
- Any omitted keys will be removed from the dictionary.
-}
reorder : List k -> AllDictList k v comparable -> AllDictList k v comparable
reorder newKeys dictlist =
-- Conceptually, the easiest way to implement this is just to walk through
-- the new keys and build up the new dict by picking out values from the
-- old dict. That should be about as efficient as we can make this. We do a
-- `foldr` so that we can do an efficient `cons` to build up the new dict.
-- It's possible that we could optimize this by acting on the dict and the
-- list separately, but not obvious.
let
go key acc =
case get key dictlist of
Just value ->
cons key value acc
Nothing ->
acc
in
List.foldr go (emptyWithOrdFrom dictlist) newKeys
{-| Gets the key at the specified index (0-based).
-}
getKeyAt : Int -> AllDictList k v comparable -> Maybe k
getKeyAt index (AllDictList dict list) =
List.Extra.getAt index list
{-| Gets the key and value at the specified index (0-based).
-}
getAt : Int -> AllDictList k v comparable -> Maybe ( k, v )
getAt index (AllDictList dict list) =
List.Extra.getAt index list
|> Maybe18.andThen
(\key ->
AllDict.get key dict
|> Maybe.map (\value -> ( key, value ))
)
{-| Insert a key-value pair into a dictionary, replacing an existing value if
the keys collide. The first parameter represents an existing key, while the
second parameter is the new key. The new key and value will be inserted after
the existing key (even if the new key already exists). If the existing key
cannot be found, the new key/value pair will be inserted at the end.
-}
insertAfter : k -> k -> v -> AllDictList k v comparable -> AllDictList k v comparable
insertAfter afterKey key value (AllDictList dict list) =
let
newDict =
-- No matter what we do to the list, we definitely put the new
-- value in the dict.
AllDict.insert key value dict
newList =
if AllDict.member afterKey dict then
if equalKeys key afterKey dict then
-- We're inserting the key after itself, so we can
-- short-circuit ... the list doesn't change.
list
else
let
-- We have the afterKey, and we may or may not have the
-- key already. So, we remove the key ... we'll add it
-- back in after the afterKey
listWithoutKey =
removeKey key dict list
ord =
AllDict.getOrd dict
afterKeyComparable =
ord afterKey
in
-- We need to find the afterKey
case List.Extra.findIndex (\k -> ord k == afterKeyComparable) listWithoutKey of
Just index ->
-- We found the existing element, so take apart
-- the list and put it back together, with our
-- key in the right place
List.take (index + 1) listWithoutKey
++ (key :: List.drop (index + 1) listWithoutKey)
Nothing ->
-- This shouldn't happen, since we tested that
-- the afterKey was present. So, crash.
Debug.crash "Internal error: AllDictList list not in sync with dict"
else
-- We didn't have the afterKey. So, just remove the key (in
-- case it is present) and add it to the end.
removeKey key dict list ++ [ key ]
in
AllDictList newDict newList
{-| Insert a key-value pair into a dictionary, replacing an existing value if
the keys collide. The first parameter represents an existing key, while the
second parameter is the new key. The new key and value will be inserted before
the existing key (even if the new key already exists). If the existing key
cannot be found, the new key/value pair will be inserted at the beginning.
-}
insertBefore : k -> k -> v -> AllDictList k v comparable -> AllDictList k v comparable
insertBefore beforeKey key value (AllDictList dict list) =
let
newDict =
-- No matter what we do to the list, we definitely put the new
-- value in the dict.
AllDict.insert key value dict
newList =
if AllDict.member beforeKey dict then
if equalKeys key beforeKey dict then
-- We're inserting the key after itself, so we can
-- short-circuit ... the list doesn't change.
list
else
let
-- We have the beforeKey, and we may or may not have
-- the key already. So, we remove the key ... we'll
-- add it back in before the beforeKey
listWithoutKey =
removeKey key dict list
ord =
AllDict.getOrd dict
beforeKeyComparable =
ord beforeKey
in
-- We need to find the beforeKey
case List.Extra.findIndex (\k -> ord k == beforeKeyComparable) listWithoutKey of
Just index ->
-- We found the existing element, so take apart
-- the list and put it back together, with our
-- key in the right place
List.take index listWithoutKey
++ (key :: List.drop index listWithoutKey)
Nothing ->
-- This shouldn't happen, since we tested that
-- the afterKey was present. So, crash.
Debug.crash "Internal error: AllDictList list not in sync with dict"
else
-- We didn't have the beforeKey. So, just remove the key (in
-- case it is present) and add it to the beginning.
key :: removeKey key dict list
in
AllDictList newDict newList
{-| Get the position of a key relative to the previous key (or next, if the
first key). Returns `Nothing` if the key was not found.
-}
relativePosition : k -> AllDictList k v comparable -> Maybe (RelativePosition k)
relativePosition key dictlist =
case previous key dictlist of
Just ( previousKey, _ ) ->
Just (AfterKey previousKey)
Nothing ->
case next key dictlist of
Just ( nextKey, _ ) ->
Just (BeforeKey nextKey)
Nothing ->
Nothing
{-| Gets the key-value pair currently at the indicated relative position.
-}
atRelativePosition : RelativePosition k -> AllDictList k v comparable -> Maybe ( k, v )
atRelativePosition position dictlist =
case position of
BeforeKey beforeKey ->
previous beforeKey dictlist
AfterKey afterKey ->
next afterKey dictlist
{-| Insert a key-value pair into a dictionary, replacing an existing value if
the keys collide. The first parameter represents an existing key, while the
second parameter is the new key. The new key and value will be inserted
relative to the existing key (even if the new key already exists). If the
existing key cannot be found, the new key/value pair will be inserted at the
beginning (if the new key was to be before the existing key) or the end (if the
new key was to be after).
-}
insertRelativeTo : RelativePosition k -> k -> v -> AllDictList k v comparable -> AllDictList k v comparable
insertRelativeTo position =
case position of
BeforeKey beforeKey ->
insertBefore beforeKey
AfterKey afterKey ->
insertAfter afterKey
----------------
-- From `AllDict`
----------------
{-| Create an empty dictionary using a given ord function to calculate hashes.
-}
empty : (k -> comparable) -> AllDictList k v comparable
empty ord =
AllDictList (AllDict.empty ord) []
{-| Element equality. Does not check equality of the ord functions.
-}
eq : AllDictList k v comparable -> AllDictList k v comparable -> Bool
eq first second =
(toList first) == (toList second)
{-| Element equality, according to the ord functions.
-}
fullEq : AllDictList k v comparable -> AllDictList k v comparable -> Bool
fullEq first second =
let
firstWithOrd =
List.map (Tuple.mapFirst (getOrd first)) (toList first)
secondWithOrd =
List.map (Tuple.mapFirst (getOrd second)) (toList second)
in
firstWithOrd == secondWithOrd
{-| Get the ord function used by the dictionary.
-}
getOrd : AllDictList k v comparable -> (k -> comparable)
getOrd (AllDictList dict list) =
AllDict.getOrd dict
{-| Get the value associated with a key. If the key is not found, return
`Nothing`.
-}
get : k -> AllDictList k v comparable -> Maybe v
get key (AllDictList dict list) =
-- So, this is basically the key thing that is optimized, compared
-- to an association list.
AllDict.get key dict
{-| Determine whether a key is in the dictionary.
-}
member : k -> AllDictList k v comparable -> Bool
member key (AllDictList dict list) =
AllDict.member key dict
{-| Determine the number of key-value pairs in the dictionary.
-}
size : AllDictList k v comparable -> Int
size (AllDictList dict list) =
AllDict.size dict
{-| Determine whether a dictionary is empty.
-}
isEmpty : AllDictList k v comparable -> Bool
isEmpty (AllDictList dict list) =
List.isEmpty list
{-| Insert a key-value pair into a dictionary. Replaces the value when the
keys collide, leaving the keys in the same order as they had been in.
If the key did not previously exist, it is added to the end of
the list.
-}
insert : k -> v -> AllDictList k v comparable -> AllDictList k v comparable
insert key value (AllDictList dict list) =
let
newDict =
AllDict.insert key value dict
newList =
if AllDict.member key dict then
-- We know this key, so leave it where it was
list
else
-- We don't know this key, so also insert it at the end of the list.
list ++ [ key ]
in
AllDictList newDict newList
{-| Remove a key-value pair from a dictionary. If the key is not found,
no changes are made.
-}
remove : k -> AllDictList k v comparable -> AllDictList k v comparable
remove key (AllDictList dict list) =
AllDictList
(AllDict.remove key dict)
(removeKey key dict list)
{-| Update the value for a specific key with a given function. Maintains
the order of the key, or inserts it at the end if it is new.
-}
update : k -> (Maybe v -> Maybe v) -> AllDictList k v comparable -> AllDictList k v comparable
update key alter dictList =
case alter (get key dictList) of
Nothing ->
remove key dictList
Just value ->
insert key value dictList
{-| Create a dictionary with one key-value pair.
-}
singleton : (k -> comparable) -> k -> v -> AllDictList k v comparable
singleton ord key value =
AllDictList (AllDict.singleton ord key value) [ key ]
-- COMBINE
{-| Combine two dictionaries. If keys collide, preference is given
to the value from the first dictionary.
Keys already in the first dictionary will remain in their original order.
Keys newly added from the second dictionary will be added at the end.
So, you might think of `union` as being biased towards the first argument,
since it preserves both key-order and values from the first argument, only
adding things on the right (from the second argument) for keys that were not
present in the first. This seems to correspond best to the logic of `AllDict.union`.
For a similar function that is biased towards the second argument, see `append`.
-}
union : AllDictList k v comparable -> AllDictList k v comparable -> AllDictList k v comparable
union t1 t2 =
foldr cons t2 t1
{-| Keep a key-value pair when its key appears in the second dictionary.
Preference is given to values in the first dictionary. The resulting
order of keys will be as it was in the first dictionary.
-}
intersect : AllDictList k v comparable -> AllDictList k v comparable -> AllDictList k v comparable
intersect t1 t2 =
filter (\k _ -> member k t2) t1
{-| Keep a key-value pair when its key does not appear in the second dictionary.
-}
diff : AllDictList k v comparable -> AllDictList k v comparable -> AllDictList k v comparable
diff t1 t2 =
foldl (\k v t -> remove k t) t1 t2
{-| The most general way of combining two dictionaries. You provide three
accumulators for when a given key appears:
1. Only in the left dictionary.
2. In both dictionaries.
3. Only in the right dictionary.
You then traverse all the keys and values, building up whatever
you want.
The keys and values from the first dictionary will be provided first,
in the order maintained by the first dictionary. Then, any keys which are
only in the second dictionary will be provided, in the order maintained
by the second dictionary.
-}
merge :
(k -> a -> result -> result)
-> (k -> a -> b -> result -> result)
-> (k -> b -> result -> result)
-> AllDictList k a comparable
-> AllDictList k b comparable