/
enumerable.fy
903 lines (724 loc) · 21.2 KB
/
enumerable.fy
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
class Fancy {
class Enumerable {
"""
Mixin-Class with useful methods for collections that implement an @each:@ method.
"""
expects_interface: 'each:
def at: index {
"""
@index @Fixnum@ that is the 0-based index into @self.
@return Value in @self at 0-based position defined by @index.
Example:
\"foo\” at: 2 # => \"o\"
\"foo\” at: 3 # => nil
"""
each_with_index: |x i| {
{ return x } if: $ i == index
}
return nil
}
def each_with_index: block {
"""
@block @Block@ to be called with each element and its index in the @self.
@return @self
Iterate over all elements in @self.
Calls a given @Block@ with each element and its index.
"""
i = 0
each: |x| {
block call: [x, i]
i = i + 1
}
}
def first {
"""
@return The first element in the @Fancy::Enumerable@.
"""
at: 0
}
def second {
"""
@return The second element in the @Fancy::Enumerable@.
"""
at: 1
}
def third {
"""
@return The third element in the @Fancy::Enumerable@.
"""
at: 2
}
def fourth {
"""
@return The fourth element in the @Fancy::Enumerable@.
"""
at: 3
}
def last {
"""
@return Last element in @self or @nil, if empty.
Returns the last element in a @Fancy::Enumerable@.
"""
item = nil
each: |x| {
item = x
}
item
}
def rest {
"""
@return @Array@ of all but the first element in @self.
"""
drop: 1
}
def first: amount {
"""
@amount Amount of first elements to take from @self.
@return @Array@ of first @amount elements in @self.
Example:
(1,2,3,4) first: 2 # => [1,2]
"""
i = 0
take_while: {
i = i + 1
i <= amount
}
}
def last: amount {
"""
@amount Amount of last elements to take from @self.
@return @Array@ of last @amount elements in @self.
Example:
(1,2,3,4) last: 2 # => [3,4]
"""
start_index = size - amount
i = 0
drop_while: {
i = i + 1
i <= start_index
}
}
def includes?: item {
"""
@item Item to check if it's included in @self.
@return @true, if @item in @self, otherwise @false.
Indicates, if a collection includes a given element.
"""
any?: |x| { x == item }
}
def each: each_block in_between: between_block {
"""
Similar to @each:@ but calls an additional @Block@ between
calling the first @Block@ for each element in self.
"""
between = { between = between_block }
each: |x| {
between call
each_block call: [x]
}
}
def join: str ("") {
"""
@str Value (usually a @String@) to be used for the joined @String@.
@return @String@ containing all elements in @self interspersed with @str.
Joins a collection with a @String@ between each element, returning a new @String@.
\"hello, world\" join: \"-\" # => \"h-e-l-l-o-,- -w-o-r-l-d\"
"""
s = ""
each: |c| {
s << c
} in_between: {
s << str
}
s
}
def join_by: block {
"""
@block @Block@ to be called pair-wise to produce a single value.
@return Result of calling @block pairwise (similar to using @Fancy::Enumerable#reduce:into:@).
Works similar to @Fancy::Enumerable#inject:into:@ but uses first element as value injected.
Example:
(1,2,3) reduce_by: '+ # => same as: (2,3) inject: 1 into: '+
"""
first, *rest = self
rest inject: first into: block
}
def any?: condition {
"""
@condition @Block@ (or @Callable) that is used to check if any element in @self yields true for it.
@return @true, if @condition yields @true for any element, @false otherwise.
Indicates, if any element meets the condition.
"""
each: |x| {
if: (condition call: [x]) then: {
return true
}
}
false
}
def all?: condition {
"""
@block Predicate @Block@ to be called for each element until it returns @false for any one of them.
@return @true if all elements in @self yield @true for @block, @false otherwise.
Takes condition-block and returns @true if all elements meet it.
"""
each: |x| {
unless: (condition call: [x]) do: {
return false
}
}
true
}
def find: item {
"""
@item Item to be found in @self.
@return The first element that is equal to @item or @nil, if none found.
Returns @nil, if @item (or anything that returns @true when comparing to @item) isn't found.
Otherwise returns that element that is equal to @item.
"""
if: (item is_a?: Block) then: {
find_by: item
} else: {
each: |x| {
if: (item == x) then: {
return x
}
}
nil
}
}
def find: item do: block {
"""
@item Item to find in @self.
@block @Block@ to be called with @item if found in @self.
Calls @block with @item, if found.
If @item is not in @self, @block is not called.
"""
if: (find: item) then: block
}
def find_with_index: item do: block {
"""
@item Item to find in @self.
@block @Block@ to be called with @item and its index in @self.
Calls @block with @item and its index in @self, if found.
If @item is not in @self, @block is not called.
"""
for_every: item with_index_do: |x i| {
return block call: [x, i]
}
nil
}
def for_every: item with_index_do: block {
"""
@item Item to call @block with.
@block @Block@ to be called with @item and each of its indexes in @self.
Calls @block with @item and each of its indexes in @self, if @item is in @self.
"""
each_with_index: |x i| {
if: (item == x) then: {
block call: [x, i]
}
}
}
def for_every: item do: block {
"""
@item Item to call @block with.
@block @Block@ to be called with @item for every occurance of @item in @self.
Calls @block with @item for each occurance of @item in @self.
Example:
count = 0
[1,2,3,2,1] for_every: 1 do: { count = count + 1 }
# count is now 2
"""
each: |x| {
if: (item == x) then: { block call: [x] }
}
}
def last_index_of: item {
"""
@item Item for which the last index in @self should be found.
@return Last index of @item in @self, or @nil (if not in @self).
Returns the last index for @item in @self, or @nil, if @item is not in @self.
"""
last_idx = nil
for_every: item with_index_do: |_ i| { last_idx = i }
last_idx
}
def find_by: block {
"""
Similar to @find:@ but takes a block that is called for each element to find it.
"""
each: |x| {
if: (block call: [x]) then: {
return x
}
}
nil
}
def map: block {
"""
@block A @Block@ that gets called with each element in @self.
@return An @Array@ containing all values of calling @block with each element in @self.
Returns a new @Array@ with the results of calling a given block for every element.
"""
coll = []
each: |x| {
coll << (block call: [x])
}
coll
}
def map_with_index: block {
"""
@block A @Block@ that gets called with each element and its index in @self.
@return An @Array@ containing all values of calling @block with each element and its index in @self.
Returns a new @Array@ with the results of calling a given block for every element and its index.
"""
coll = []
each_with_index: |x i| {
coll << (block call: [x, i])
}
coll
}
def map_chained: blocks {
"""
@blocks Collection of @Block@s to be called sequentially for every element in @self.
@return Collection of all values in @self successively called with all blocks in @blocks.
Example:
(1,2,3) map_chained: (@{ + 1 }, 'to_s, @{ * 2 })
# => [\"22\", \"33\", \"44\"]
"""
map: |v| {
blocks inject: v into: |acc b| {
b call: [acc]
}
}
}
def flat_map: block {
"""
Similar to @Fancy::Enumerable#map:@ but returns the result @Array@ flattened.
"""
map: block . tap: @{ flatten! }
}
def select: condition {
"""
@condition A @Block@ that is used as a filter on all elements in @self.
@return An @Array@ containing all elements in @self that yield @true when called with @condition.
Returns a new @Array@ with all elements that meet the given condition block.
"""
coll = []
each: |x| {
{ coll << x } if: $ condition call: [x]
}
coll
}
def select_with_index: condition {
"""
@condition A @Block@ that is used as a filter on all elements in @self.
@return An @Array@ containing all elements and their indices in @self that yield @true when called with @condition.
Returns a new @Array@ with all elements and their indices that meet the given condition block.
@condition is called with each element and its index in @self.
"""
tmp = []
each_with_index: |obj idx| {
if: (condition call: [obj, idx]) then: {
tmp << [obj, idx]
}
}
tmp
}
def reject: condition {
"""
Similar to @select:@ but inverse.
Returns a new @Array@ with all elements that don't meet the given condition block.
"""
coll = []
each: |x| {
{ coll << x } unless: $ condition call: [x]
}
coll
}
def take_while: condition {
"""
@condition A @Block@ that is used as a condition for filtering.
@return An @Array@ of all elements from the beginning until @condition yields @false.
Returns a new @Array@ by taking elements from the beginning
as long as they meet the given condition block.
Example:
[1,2,3,4,5] take_while: |x| { x < 4 } # => [1,2,3]
"""
coll = []
each: |x| {
if: (condition call: [x]) then: {
coll << x
} else: {
return coll
}
}
coll
}
def drop_while: condition {
"""
Similar to @take_while:@ but inverse.
Returns a new @Array@ by skipping elements from the beginning
as long as they meet the given condition block.
Example:
[1,2,3,4,5] drop_while: |x| { x < 4 } # => [4,5]
"""
coll = []
drop = nil
first_check = true
each: |x| {
if: (drop or: first_check) then: {
drop = condition call: [x]
first_check = nil
# check, if we actually have to insert this one:
unless: drop do: {
coll << x
}
} else: {
coll << x
}
}
coll
}
def take: amount {
"""
@amount Amount of elements to take from @self.
@return @Array@ of first @amount elements in @self.
Example:
[1,2,3,4] take: 2 # => [1,2]
"""
i = 0
take_while: {
i = i + 1
i <= amount
}
}
def drop: amount {
"""
@amount Amount of elements to skip in @self.
@return An @Array@ of all but the first @amount elements in @self.
Example:
[1,2,3,4,5] drop: 2 # => [3,4,5]
"""
i = 0
drop_while: {
i = i + 1
i <= amount
}
}
alias_method: 'skip: for: 'drop:
def reduce: block init_val: init_val {
"""
Calculates a value based on a given block to be called on an accumulator
value and an initial value.
Example:
[1,2,3] reduce: |sum val| { sum + val } init_val: 0 # => 6
"""
acc = init_val
each: |x| {
acc = block call: [acc, x]
}
acc
}
def inject: val into: block {
"""
Same as reduce:init_val: but taking the initial value as first
and the reducing block as second parameter.
Example:
[1,2,3] inject: 0 into: |sum val| { sum + val } # => 6
"""
reduce: block init_val: val
}
def unique {
"""
@return @Array@ of all unique elements in @self.
Returns a new Array with all unique values (double entries are skipped).
Example:
[1,2,1,2,3] unique # => [1,2,3]
"""
unique_vals = []
each: |x| {
unless: (unique_vals includes?: x) do: {
unique_vals << x
}
}
unique_vals
}
def size {
"""
@return Amount of elements in @self.
Returns the size of an Enumerable.
"""
i = 0
each: {
i = i + 1
}
i
}
def empty? {
"""
@return @true, if size of @self is 0, @false otherwise.
Indicates, if the Enumerable is empty (has no elements).
"""
size == 0
}
def compact {
"""
@return @Array@ with all non-nil elements in @self.
Returns a new @Array@ with all values removed that are @nil ( return @true on @nil? ).
Example:
[1,2,nil,3,nil] compact # => [1,2,3]
"""
reject: @{ nil? }
}
def superior_by: comparison_block taking: selection_block (@{ identity }) {
"""
@comparison_block @Block@ to be used for comparison.
@selection_block @Block@ to be used for selecting the values to be used for comparison by @comparison_block.
@return Superior element in @self in terms of @comparison_block.
Returns the superior element in the @Fancy::Enumerable@ that has met
the given comparison block with all other elements,
applied to whatever @selection_block returns for each element.
@selection_block defaults to @identity.
Examples:
[1,2,5,3,4] superior_by: '> # => 5
[1,2,5,3,4] superior_by: '< # => 1
[[1,2], [2,3,4], [], [1]] superior_by: '> taking: 'size # => [2,3,4]
[[1,2], [2,3,4], [-1]] superior_by: '< taking: 'first # => [-1]
"""
pairs = self map: |val| {
(val, selection_block call: [val])
}
retval = pairs first
pairs each: |p| {
if: (comparison_block call: [p second, retval second]) then: {
retval = p
}
}
retval first
}
def max {
"""
@return Maximum value in @self.
Returns the maximum value in the Enumerable (via the '>' comparison message).
"""
superior_by: '>
}
def min {
"""
@return Minimum value in @self.
Returns the minimum value in the Enumerable (via the '<' comparison message).
"""
superior_by: '<
}
def sum {
"""
Calculates the sum of all the elements in the @Enumerable
(assuming them to be @Number@s (implementing '+' & '*')).
"""
inject: 0 into: '+
}
def product {
"""
Calculates the product of all the elements in the @Enumerable
(assuming them to be @Number@s (implementing @+ & @*)).
"""
inject: 1 into: '*
}
def average {
"""
@return Average value in @self (expecting @Number@s or Objects implementing @+ and @*).
"""
{ return 0 } if: (size == 0)
sum to_f / size
}
def partition_by: block {
"""
@block @Block@ that gets used to decide when to partition elements in @self.
@return @Array@ of @Array@s, partitioned by equal return values of calling @block with each element
Example:
(0..10) partition_by: @{ < 3 } # => [[0, 1, 2], [3, 4, 5, 6, 7, 8, 9, 10]]
"""
last = block call: [first]
coll = []
tmp_coll = []
each: |x| {
tmp = block call: [x]
if: (tmp != last) then: {
coll << tmp_coll
tmp_coll = [x]
} else: {
tmp_coll << x
}
last = tmp
}
coll << tmp_coll
coll
}
def random {
"""
@return Random element in @self.
"""
at: $ size random
}
def sort_by: block {
"""
@block @Block@ taking 2 arguments used to compare elements in a collection.
@return Sorted @Array@ of elements in @self.
Sorts a collection by a given comparison block.
"""
if: (block is_a?: Symbol) then: {
sort() |a b| {
a receive_message: block . <=> (b receive_message: block)
}
} else: {
sort(&block)
}
}
def in_groups_of: size {
"""
@size Maximum size of each group.
@return @Array@ of @Array@s with a max size of @size (grouped).
Example usage:
[1,2,3,4,5] in_groups_of: 3 # => [[1,2,3],[4,5]]
"""
groups = []
tmp = []
enum = to_enum
{ return groups } if: (size <= 0)
loop: {
size times: {
tmp << (enum next)
}
if: (enum ended?) then: {
{ groups << tmp } unless: $ tmp empty?
break
}
groups << tmp
tmp = []
}
groups
}
def reverse {
"""
@return @self in reverse order.
Returns @self in reverse order.
This only makes sense for collections that have an ordering.
In either case, it simply converts @self to an @Array@ and returns it in reversed order.
"""
self to_a reverse
}
def to_hash: block {
"""
@block @Block@ to be called to get the key for each element in @self.
@return @Hash@ of key/value pairs based on values in @self.
Example:
[\"foo\", \”hello\", \"ok\", \"\"] to_hash: @{ size }
# => <[3 => \"foo\", 5 => \"hello\", 2 => \"ok\", 0 => \"\"]>
"""
inject: <[]> into: |h val| {
key = block call: [val]
h[key]: val
h
}
}
def reverse_each: block {
"""
@block @Block@ to be called for each element in reverse order.
@return @self
Runs @block for each element on reversed version of self.
If @self is not a sorted collection, no guarantees about the reverse order can be given.
"""
reverse each: block
}
def count: block {
"""
@block Predicate @Block@ called with each element.
@return @Fixnum@ that is the amount of elements in @self for which @block yields @true.
Example:
(0..10) count: @{ even? } # => 6 (even numbers are: 0,2,4,6,8,10)
[1,2,3] count: @{ odd? } # => 2
[1,2, \"foo\"] count: @{ class == String } # => 1
"""
count = 0
each: |x| {
{ count = count + 1 } if: $ block call: [x]
}
count
}
def to_s {
"""
@return @String@ concatenation of elements in @self.
Example:
(1,2,3) to_s # => \"123\"
[1,2,3] to_s # => \"123\"
\"foo\" to_s # => \"foo\"
"""
join
}
def sorted? {
"""
@return @true if @self is sorted, @false otherwise.
Example:
(1,2,3) sorted? # => true
(2,1,3) sorted? # => false
\"abc\" sorted? # => true
\"bac\" sorted? # => false
"""
last = nil
each: |x| {
if: last then: {
{ return false } unless: $ last <= x
}
last = x
}
true
}
def split_at: index {
"""
@index Index at which @self should be split.
@return @Array@ of 2 @Array@s of elements in self splitted at @index.
Example:
[1,2,3,4,5] split_at: 2 # => [[1,2], [3,4,5]]
"""
[take: index, drop: index]
}
def split_with: predicate_block {
"""
@predicate_block @Block@ to be used as a predicate on where to split in @self.
@return @Array@ of 2 @Array@s of elements split based on @predicate_block.
Example:
[1,2,3,4,5] split_with: @{ < 3 } # => [[1, 2], [3, 4, 5]]
"""
[take_while: predicate_block, drop_while: predicate_block]
}
def grep: pattern {
"""
@pattern Pattern to be filtered by (via @Object#===@)
@return Elements in @self for which @pattern matches.
Example:
\"hello world\" grep: /[a-h]/ # => [\"h\", \"e\", \"d\"]
[\"hello\", \"world\", 1, 2, 3] grep: String # => [\"hello\", \"world\"]
"""
select: |x| { pattern === x }
}
def grep: pattern taking: block {
"""
@pattern Pattern to be filtered by (via @Object#===@)
@block @Block@ to be called with each element for which @pattern matches.
@return Return values of elements in @self called with @block for which @pattern matches.
Example:
\"hello world\" grep: /[a-h]/ taking: @{ upcase } # => [\"H\", \"E\", \"D\"]
[\"hello\", \"world\", 1, 2, 3] grep: String taking: 'upcase # => [\"HELLO\", \"WORLD\"]
"""
result = []
each: |x| {
match x {
case pattern -> result << (block call: [x])
}
}
result
}
}
}