-
Notifications
You must be signed in to change notification settings - Fork 59
/
Extra.elm
2283 lines (1654 loc) · 57.4 KB
/
Extra.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 List.Extra exposing
( last, init, getAt, uncons, unconsLast, maximumBy, maximumWith, minimumBy, minimumWith, andMap, andThen, reverseMap, reverseFilter, takeWhile, dropWhile, unique, uniqueBy, allDifferent, allDifferentBy, setIf, setAt, remove, updateIf, updateAt, updateIfIndex, removeAt, removeIfIndex, filterNot, swapAt, stableSortWith
, intercalate, transpose, subsequences, permutations, interweave, cartesianProduct, uniquePairs
, foldl1, foldr1, indexedFoldl, indexedFoldr, Step(..), stoppableFoldl
, scanl, scanl1, scanr, scanr1, mapAccuml, mapAccumr, unfoldr, iterate, initialize, cycle, reverseRange
, splitAt, splitWhen, takeWhileRight, dropWhileRight, span, break, stripPrefix, group, groupWhile, inits, tails, select, selectSplit, gatherEquals, gatherEqualsBy, gatherWith, subsequencesNonEmpty, frequencies
, isPrefixOf, isSuffixOf, isInfixOf, isSubsequenceOf, isPermutationOf
, notMember, find, elemIndex, elemIndices, findIndex, findIndices, findMap, count
, zip, zip3
, lift2, lift3, lift4
, groupsOf, groupsOfWithStep, groupsOfVarying, greedyGroupsOf, greedyGroupsOfWithStep
, joinOn
)
{-| Convenience functions for working with List
# Basics
@docs last, init, getAt, uncons, unconsLast, maximumBy, maximumWith, minimumBy, minimumWith, andMap, andThen, reverseMap, reverseFilter, takeWhile, dropWhile, unique, uniqueBy, allDifferent, allDifferentBy, setIf, setAt, remove, updateIf, updateAt, updateIfIndex, removeAt, removeIfIndex, filterNot, swapAt, stableSortWith
# List transformations
@docs intercalate, transpose, subsequences, permutations, interweave, cartesianProduct, uniquePairs
# Folds
@docs foldl1, foldr1, indexedFoldl, indexedFoldr, Step, stoppableFoldl
# Building lists
@docs scanl, scanl1, scanr, scanr1, mapAccuml, mapAccumr, unfoldr, iterate, initialize, cycle, reverseRange
# Sublists
@docs splitAt, splitWhen, takeWhileRight, dropWhileRight, span, break, stripPrefix, group, groupWhile, inits, tails, select, selectSplit, gatherEquals, gatherEqualsBy, gatherWith, subsequencesNonEmpty, frequencies
# Predicates
@docs isPrefixOf, isSuffixOf, isInfixOf, isSubsequenceOf, isPermutationOf
# Searching
@docs notMember, find, elemIndex, elemIndices, findIndex, findIndices, findMap, count
# Zipping
@docs zip, zip3
# Lift functions onto multiple lists of arguments
@docs lift2, lift3, lift4
# Split to groups of given size
@docs groupsOf, groupsOfWithStep, groupsOfVarying, greedyGroupsOf, greedyGroupsOfWithStep
# Joins
@docs joinOn
-}
import List exposing (..)
import Tuple exposing (first, second)
{-| Extract the last element of a list.
last [ 1, 2, 3 ]
--> Just 3
last []
--> Nothing
-}
last : List a -> Maybe a
last items =
case items of
[] ->
Nothing
[ x ] ->
Just x
_ :: rest ->
last rest
{-| Return all elements of the list except the last one.
init [ 1, 2, 3 ]
--> Just [ 1, 2 ]
init []
--> Nothing
-}
init : List a -> Maybe (List a)
init items =
case items of
[] ->
Nothing
nonEmptyList ->
nonEmptyList
|> List.reverse
|> List.tail
|> Maybe.map List.reverse
{-| Returns `Just` the element at the given index in the list,
or `Nothing` if the index is out of range.
-}
getAt : Int -> List a -> Maybe a
getAt idx xs =
if idx < 0 then
Nothing
else
List.head <| List.drop idx xs
{-| Returns a list of repeated applications of `f`. If `f` returns `Nothing`
the iteration will stop. If it returns `Just y` then `y` will be added to the
list and the iteration will continue with `f y`.
collatz : Int -> Maybe Int
collatz n =
if n == 1 then
Nothing
else
Just <|
if modBy 2 n == 0 then
n // 2
else
3 * n + 1
iterate collatz 13
--> [13,40,20,10,5,16,8,4,2,1]
-}
iterate : (a -> Maybe a) -> a -> List a
iterate f x =
iterateHelp f x [] |> List.reverse
iterateHelp : (a -> Maybe a) -> a -> List a -> List a
iterateHelp f x acc =
case f x of
Just x_ ->
iterateHelp f x_ (x :: acc)
Nothing ->
x :: acc
{-| Initialize a list of some length with some function.
`initialize n f` creates a list of length `n` with the element at index `i` initialized to the result of `f i`.
-}
initialize : Int -> (Int -> a) -> List a
initialize n f =
let
step i acc =
if i < 0 then
acc
else
step (i - 1) (f i :: acc)
in
step (n - 1) []
{-| Creates a list of the given length whose elements are obtained by cycling
through the elements of the given list. If the given list is empty, the
resulting list will be empty.
cycle 6 [ 4, 7, 8 ]
--> [ 4, 7, 8, 4, 7, 8 ]
cycle 4 [ 'a', 'b', 'c' ]
--> [ 'a', 'b', 'c', 'a' ]
cycle 9001 []
--> []
cycle 2 [ 1, 2, 3, 4, 5 ]
--> [ 1, 2 ]
-}
cycle : Int -> List a -> List a
cycle len list =
let
cycleLength =
List.length list
in
if cycleLength == 0 || cycleLength == len then
list
else if cycleLength < len then
List.reverse
(reverseAppend
(List.take (remainderBy cycleLength len) list)
(cycleHelp [] (len // cycleLength) list)
)
else
List.take len list
cycleHelp : List a -> Int -> List a -> List a
cycleHelp acc n list =
if n > 0 then
cycleHelp (reverseAppend list acc) (n - 1) list
else
acc
{-| Create a list of numbers, every element decreasing by one.
You give the highest and lowest number that should be in the list.
More efficient than calling `List.reverse (List.range lo hi)`
range 6 3 == [ 6, 5, 4, 3 ]
range 3 3 == [ 3 ]
range 3 6 == []
-}
reverseRange : Int -> Int -> List Int
reverseRange =
let
helper : List Int -> Int -> Int -> List Int
helper list high low =
if high >= low then
helper (low :: list) high (low + 1)
else
list
in
helper []
{-| Decompose a list into its head and tail. If the list is empty, return `Nothing`. Otherwise, return `Just (x, xs)`, where `x` is head and `xs` is tail.
uncons [1,2,3]
--> Just (1, [2,3])
uncons []
--> Nothing
-}
uncons : List a -> Maybe ( a, List a )
uncons list =
case list of
[] ->
Nothing
first :: rest ->
Just ( first, rest )
{-| Decompose a list into its body and last element. If the list is empty, return `Nothing`. Otherwise, return `Just (x, xs)`, where `x` is the last element and `xs` is the body.
unconsLast [1,2,3]
--> Just (3, [1,2])
unconsLast []
--> Nothing
-}
unconsLast : List a -> Maybe ( a, List a )
unconsLast list =
case List.reverse list of
[] ->
Nothing
last_ :: rest ->
( last_, List.reverse rest )
|> Just
{-| Find the first maximum element in a list using a comparable transformation
-}
maximumBy : (a -> comparable) -> List a -> Maybe a
maximumBy f ls =
let
maxBy : a -> ( a, comparable ) -> ( a, comparable )
maxBy x (( _, fy ) as max) =
let
fx : comparable
fx =
f x
in
if fx > fy then
( x, fx )
else
max
in
case ls of
[ l_ ] ->
Just l_
l_ :: ls_ ->
Just <| first <| foldl maxBy ( l_, f l_ ) ls_
_ ->
Nothing
{-| Find the first maximum element in a list using a comparison function
maximumWith compare []
--> Nothing
maximumWith
(\x y -> compare x.val y.val)
[{id=1, val=1}, {id=2, val=2}, {id=3,val=2}]
--> Just { id = 2, val = 2 }
-}
maximumWith : (a -> a -> Order) -> List a -> Maybe a
maximumWith comparator list =
foldl1
(\x y ->
case comparator x y of
GT ->
x
_ ->
y
)
list
{-| Find the first minimum element in a list using a comparable transformation
-}
minimumBy : (a -> comparable) -> List a -> Maybe a
minimumBy f ls =
let
minBy : a -> ( a, comparable ) -> ( a, comparable )
minBy x (( _, fy ) as min) =
let
fx : comparable
fx =
f x
in
if fx < fy then
( x, fx )
else
min
in
case ls of
[ l_ ] ->
Just l_
l_ :: ls_ ->
Just <| first <| foldl minBy ( l_, f l_ ) ls_
_ ->
Nothing
{-| Find the first minimum element in a list using a comparison function
minimumWith compare []
--> Nothing
minimumWith
(\x y -> compare x.val y.val)
[{id=1, val=2}, {id=2, val=1}, {id=3,val=1}]
--> Just { id = 2, val = 1 }
-}
minimumWith : (a -> a -> Order) -> List a -> Maybe a
minimumWith comparator list =
foldl1
(\x y ->
case comparator x y of
LT ->
x
_ ->
y
)
list
{-| Take elements in order as long as the predicate evaluates to `True`
-}
takeWhile : (a -> Bool) -> List a -> List a
takeWhile predicate =
let
takeWhileMemo memo list =
case list of
[] ->
List.reverse memo
x :: xs ->
if predicate x then
takeWhileMemo (x :: memo) xs
else
List.reverse memo
in
takeWhileMemo []
{-| Drop elements in order as long as the predicate evaluates to `True`
-}
dropWhile : (a -> Bool) -> List a -> List a
dropWhile predicate list =
case list of
[] ->
[]
x :: xs ->
if predicate x then
dropWhile predicate xs
else
list
{-| Remove duplicate values, keeping the first instance of each element which appears more than once.
unique [ 0, 1, 1, 0, 1 ]
--> [ 0, 1 ]
-}
unique : List a -> List a
unique list =
uniqueHelp identity [] list []
{-| Drop duplicates where what is considered to be a duplicate is the result of first applying the supplied function to the elements of the list.
-}
uniqueBy : (a -> b) -> List a -> List a
uniqueBy f list =
uniqueHelp f [] list []
{-| Indicate if list has duplicate values.
allDifferent [ 0, 1, 1, 0, 1 ]
--> False
allDifferent [ 0, 1, 2]
--> True
-}
allDifferent : List a -> Bool
allDifferent list =
allDifferentBy identity list
{-| Indicate if list has duplicate values when supplied function are applied on each values.
-}
allDifferentBy : (a -> b) -> List a -> Bool
allDifferentBy f list =
List.length list == List.length (uniqueBy f list)
uniqueHelp : (a -> b) -> List b -> List a -> List a -> List a
uniqueHelp f existing remaining accumulator =
case remaining of
[] ->
List.reverse accumulator
first :: rest ->
let
computedFirst =
f first
in
if List.member computedFirst existing then
uniqueHelp f existing rest accumulator
else
uniqueHelp f (computedFirst :: existing) rest (first :: accumulator)
{-| Map functions taking multiple arguments over multiple lists. Each list should be of the same length.
toIntFunctions : List (Float -> Int)
toIntFunctions =
[ round
, floor
, ceiling
, truncate
]
toIntFunctions
|> andMap [ -1.5, -1.5, -1.5, -1.5 ]
--> [ -1, -2, -1, -1 ]
math : List (Int -> Int)
math =
[ (+) 1
, (*) 2
, (*) 3 >> (+) 1
]
math
|> andMap [ 1, 2, 3 ]
--> [ 2, 4, 10 ]
-}
andMap : List a -> List (a -> b) -> List b
andMap l fl =
map2 (<|) fl l
{-| Equivalent to `concatMap`. For example, suppose you want to have a cartesian product of [1,2] and [3,4]:
[ 1, 2 ]
|> andThen
(\x ->
[ 3, 4 ]
|> andThen (\y -> [ ( x, y ) ])
)
--> [ ( 1, 3 ), ( 1, 4 ), ( 2, 3 ), ( 2, 4 ) ]
Now suppose we want to have a cartesian product between the first list and the second list and its doubles:
[ 1, 2 ]
|> andThen
(\x ->
[ 3, 4 ]
|> andThen
(\y ->
[ y, y * 2 ]
|> andThen (\z -> [ ( x, z ) ])
)
)
--> [ ( 1, 3 ), ( 1, 6 ), ( 1, 4 ), ( 1, 8 ), ( 2, 3 ), ( 2, 6 ), ( 2, 4 ), ( 2, 8 )]
Advanced functional programmers will recognize this as the implementation of bind operator (>>=) for lists from the `Monad` typeclass.
-}
andThen : (a -> List b) -> List a -> List b
andThen =
concatMap
{-| `reverseMap f xs` gives the same result as `List.reverse (List.map f xs)`,
but is tail-recursive and slightly more efficient.
reverseMap sqrt [ 1, 4, 9 ]
--> [ 3, 2, 1 ]
-}
reverseMap : (a -> b) -> List a -> List b
reverseMap f xs =
foldl (\x acc -> f x :: acc) [] xs
{-| `reverseMap f xs` gives the same result as `List.reverse (List.map f xs)`,
but is tail-recursive and slightly more efficient.
reverseFilter (\x -> x > 5) [ 1, 4, 9, 16]
--> [ 16, 9 ]
-}
reverseFilter : (a -> Bool) -> List a -> List a
reverseFilter isGood xs =
foldl
(\x acc ->
if isGood x then
x :: acc
else
acc
)
[]
xs
{-| Negation of `member`.
notMember 1 [ 1, 2, 3 ]
--> False
notMember 4 [ 1, 2, 3 ]
--> True
-}
notMember : a -> List a -> Bool
notMember x =
not << member x
{-| Find the first element that satisfies a predicate and return
Just that element. If none match, return Nothing.
find (\num -> num > 5) [ 2, 4, 6, 8 ]
--> Just 6
-}
find : (a -> Bool) -> List a -> Maybe a
find predicate list =
case list of
[] ->
Nothing
first :: rest ->
if predicate first then
Just first
else
find predicate rest
{-| Return the index of the first occurrence of the element. Otherwise, return `Nothing`. Indexing starts from 0.
elemIndex 1 [ 1, 2, 3 ]
--> Just 0
elemIndex 4 [ 1, 2, 3 ]
--> Nothing
elemIndex 1 [ 1, 2, 1 ]
--> Just 0
-}
elemIndex : a -> List a -> Maybe Int
elemIndex x =
findIndex ((==) x)
{-| Return all indices of occurrences of the element. If element is not found, return empty list. Indexing starts from 0.
elemIndices 1 [ 1, 2, 3 ]
--> [ 0 ]
elemIndices 4 [ 1, 2, 3 ]
--> []
elemIndices 1 [ 1, 2, 1 ]
--> [ 0, 2 ]
-}
elemIndices : a -> List a -> List Int
elemIndices x =
findIndices ((==) x)
{-| Take a predicate and a list, return the index of the first element that satisfies the predicate. Otherwise, return `Nothing`. Indexing starts from 0.
isEven : Int -> Bool
isEven i =
modBy 2 i == 0
findIndex isEven [ 1, 2, 3 ]
--> Just 1
findIndex isEven [ 1, 3, 5 ]
--> Nothing
findIndex isEven [ 1, 2, 4 ]
--> Just 1
-}
findIndex : (a -> Bool) -> List a -> Maybe Int
findIndex =
findIndexHelp 0
findIndexHelp : Int -> (a -> Bool) -> List a -> Maybe Int
findIndexHelp index predicate list =
case list of
[] ->
Nothing
x :: xs ->
if predicate x then
Just index
else
findIndexHelp (index + 1) predicate xs
{-| Take a predicate and a list, return indices of all elements satisfying the predicate. Otherwise, return empty list. Indexing starts from 0.
isEven : Int -> Bool
isEven i =
modBy 2 i == 0
findIndices isEven [ 1, 2, 3 ]
--> [ 1 ]
findIndices isEven [ 1, 3, 5 ]
--> []
findIndices isEven [ 1, 2, 4 ]
--> [ 1, 2 ]
-}
findIndices : (a -> Bool) -> List a -> List Int
findIndices predicate =
let
consIndexIf index x acc =
if predicate x then
index :: acc
else
acc
in
indexedFoldr consIndexIf []
{-| Apply a function that may succeed to values in the list and return the result of the first successful match. If none match, then return Nothing.
mapOverFive : Int -> Maybe Int
mapOverFive num =
if num > 5 then
Just (num * 2)
else
Nothing
findMap mapOverFive [2, 4, 6, 8]
--> Just 12
This is particularly useful in cases where you have a complex type in a list, and you need to pick out the the first one
type alias HouseModel =
{}
type Property
= Rental
| House HouseModel
| Commercial
toHouse : Property -> Maybe HouseModel
toHouse property =
case property of
House house ->
Just house
_ ->
Nothing
viewFirstHomeOfInterest : Viewer -> List Property -> Html msg
viewFirstHomeOfInterest viewer propertiesQuery =
propertiesQuery
|> findMap toHouse
|> Maybe.map homeView
|> Maybe.withDefault noHomeView
-}
findMap : (a -> Maybe b) -> List a -> Maybe b
findMap f list =
case list of
[] ->
Nothing
a :: tail ->
case f a of
Just b ->
Just b
Nothing ->
findMap f tail
{-| Returns the number of elements in a list that satisfy a given predicate.
Equivalent to `List.length (List.filter pred list)` but more efficient.
count
(modBy 2 >> (==) 1) [ 1, 2, 3, 4, 5, 6, 7 ]
--> 4
count
((==) "yeah")
[ "She", "loves", "you", "yeah", "yeah", "yeah" ]
--> 3
-}
count : (a -> Bool) -> List a -> Int
count predicate =
List.foldl
(\x acc ->
if predicate x then
acc + 1
else
acc
)
0
{-| Replace all values that satisfy a predicate with a replacement value.
-}
setIf : (a -> Bool) -> a -> List a -> List a
setIf predicate replacement list =
updateIf predicate (always replacement) list
{-| Replace all values that satisfy a predicate by calling an update function.
-}
updateIf : (a -> Bool) -> (a -> a) -> List a -> List a
updateIf predicate update list =
List.map
(\item ->
if predicate item then
update item
else
item
)
list
{-| Replace a value at a specific index by calling an update function. Return the original list if the index is out of range.
updateAt 0 ((+) 1) [ 1, 2, 3 ]
--> [ 2, 2, 3 ]
See also `updateIfIndex`.
-}
updateAt : Int -> (a -> a) -> List a -> List a
updateAt index fn list =
if index < 0 then
list
else
let
tail : List a
tail =
List.drop index list
in
case tail of
x :: xs ->
List.take index list ++ fn x :: xs
[] ->
list
{-| Replace a value at an index that satisfies a predicate, by calling an update function.
updateIfIndex ((==) 2) ((+) 1) [ 1, 2, 3 ]
--> [ 1, 2, 4 ]
See also `updateAt`.
-}
updateIfIndex : (Int -> Bool) -> (a -> a) -> List a -> List a
updateIfIndex predicate update list =
List.indexedMap
(\i x ->
if predicate i then
update x
else
x
)
list
{-| Remove the first occurrence of a value from a list.
-}
remove : a -> List a -> List a
remove x xs =
removeHelp xs x xs []
removeHelp : List a -> a -> List a -> List a -> List a
removeHelp list x xs previousElements =
case xs of
[] ->
list
y :: ys ->
if x == y then
reverseAppend previousElements ys
else
removeHelp list x ys (y :: previousElements)
{-| Set a value in a list by index. Return the original list if the index is out of range.
setAt 0 42 [ 1, 2, 3 ]
--> [ 42, 2, 3 ]
-}
setAt : Int -> a -> List a -> List a
setAt index value =
updateAt index (always value)
{-| Similar to List.sortWith, this sorts values with a custom comparison function.
Unlike List.sortWith, this sort is guaranteed to be a stable sort.
Note that List.sortWith is faster and is preferred if sort stability is not required.
-}
stableSortWith : (a -> a -> Basics.Order) -> List a -> List a
stableSortWith pred list =
let
listWithIndex =
List.indexedMap (\i a -> ( a, i )) list
predWithIndex ( a1, i1 ) ( a2, i2 ) =
let
result =
pred a1 a2
in
case result of
Basics.EQ ->
Basics.compare i1 i2
_ ->
result
in
List.sortWith predWithIndex listWithIndex |> List.map first
{-| Swap two values in a list by index. Return the original list if the index is out of range.
If the same index is supplied twice the operation has no effect.
swapAt 1 2 [ 1, 2, 3 ]
--> [ 1, 3, 2 ]
-}
swapAt : Int -> Int -> List a -> List a
swapAt index1 index2 l =
if index1 == index2 || index1 < 0 then
l
else if index1 > index2 then
swapAt index2 index1 l
else
let
( part1, tail1 ) =
splitAt index1 l
( head2, tail2 ) =
splitAt (index2 - index1) tail1
in
case ( uncons head2, uncons tail2 ) of
( Just ( value1, part2 ), Just ( value2, part3 ) ) ->
List.concat [ part1, value2 :: part2, value1 :: part3 ]
_ ->
l
{-| Remove the element at an index from a list. Return the original list if the index is out of range.
removeAt 0 [ 1, 2, 3 ]
--> [ 2, 3 ]
See also `removeIfIndex`.
-}
removeAt : Int -> List a -> List a
removeAt index l =
if index < 0 then
l
else
case drop index l of
[] ->
l
_ :: rest ->
take index l ++ rest
{-| Remove an element at an index that satisfies a predicate.
removeIfIndex ((==) 2) [ 1, 2, 3 ]
--> [ 1, 2 ]
See also `removeAt`.
-}
removeIfIndex : (Int -> Bool) -> List a -> List a
removeIfIndex predicate =
indexedFoldr
(\index item acc ->
if predicate index then
acc