-
Notifications
You must be signed in to change notification settings - Fork 0
/
functional.lua
1888 lines (1652 loc) · 59.6 KB
/
functional.lua
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 © 2022 William Quelho Ferreira
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]
---
-- <h2>A module for functional programming utils.</h2>
-- <h3>About the module</h3>
-- <p style="text-align: justify">This module seeks to provide some utility functions and structures
-- which are too verbose in vanilla lua, in particular with regards to iteration
-- and inline function definition.</p>
-- <p style="text-align: justify">The module is writen completely in vanilla lua,
-- with no dependencies on external packages. This was a decision made for
-- portability, and has drawbacks. Since none of this was written as a C binding, it is not
-- as performant as it could be.</p>
-- <p style="text-align: justify">For example, <a href="https://github.com/luafun/luafun">luafun</a>
-- is "high-performance functional programming library for Lua designed with
-- <a href="http://luajit.org/luajit.html">LuaJIT</a>'s trace compiler in mind"
-- . If your environment allows you to use LuaJIT and performance is a
-- concern, perhaps luafun will be more suited for your needs.</p>
-- <p style="text-align: justify; background: #eeeeee; border: 1px solid black;
-- margin-left: 15%; margin-right: 15%; padding: 10px;">
-- The motivation behind this module is, again, portability.
-- If you want to embed this code on a webpage, or use it in some weird
-- system for which a C binding wouldn't work, this project is aimed
-- at you.</p>
-- <h3>Definitions</h3>
-- <h4>Array</h4>
-- <p style="text-align: justify">As lua doesn't have a dedicated array
-- type, the word "array" in this document referes to a table with contiguous
-- non-<code>nil</code> values starting at index <code>1</code>.</p>
-- <h4>Iterable</h4>
-- <p>An <code>iterable</code> refers to either of:
-- <ul>
-- <li> An array (see above); or </li>
-- <li> An instance of <code>Iterator</code>. </li>
-- </ul></p>
-- @module functional
-- @alias M
-- @release 1.6.0
-- @author William Quelho Ferreira
-- @copyright 2021
-- @license MIT
---
local M = {}
--- Module version.
M._VERSION = "1.6.0"
local exports = {}
local internal = {}
--- A lazy-loading Iterator.
-- @type Iterator
local Iterator = {}
local iter__meta = {}
local lambda_function__meta = {}
local curried_function__meta = {}
local unpack = table.unpack or unpack
--- Iterate over the given <code>iterable</code>.
-- <p>If <code>iterable</code> is an array, create an Iterator instance
-- that returns its values one by one. If it is an
-- iterator, return itself.</p>
-- @tparam iterable iterable the values to be iterated over
-- @treturn Iterator the new Iterator
function Iterator.over(iterable)
internal.assert_table(iterable, "iterable")
if internal.is_iterator(iterable) then
return iterable
else
local copy = {unpack(iterable)}
local iterator = internal.base_iter(copy, internal.iter_next, internal.iter_clone)
iterator.index = 0
return iterator
end
end
--- Retrieve the next element from the iterator, if any.
-- @return the next value in the sequence, or <code>nil</code> if there is none
function Iterator:next()
end
--- Iterate over the naturals starting at 1.
-- @treturn Iterator the counter
-- @see Iterator:take
-- @see Iterator:skip
-- @see Iterator:every
function Iterator.counter()
local iterator = internal.base_iter(nil, internal.counter_next, internal.counter_clone)
iterator.n = 0
return iterator
end
--- Create an integer iterator that goes from <code>start</code> to <code>stop</code>, <code>step</code>-wise.
-- @tparam[opt=1] integer start the start of the integer range
-- @tparam integer stop the end of the integer range (inclusive)
-- @tparam[opt=1] integer step the difference between consecutive elements
-- @treturn Iterator the new <code>@{Iterator}</code>
-- @see range
function Iterator.range(start, stop, step)
local iterator = internal.base_iter(nil, internal.range_next, internal.range_clone)
local arg1, arg2, arg3 = start, stop, step
if arg3 then
internal.assert_not_nil(arg1, "start")
internal.assert_not_nil(arg2, "stop")
start = arg1
stop = arg2
step = arg3
if step == 0 then
error("param step must not be zero")
end
else
step = 1
if arg2 then
internal.assert_not_nil(arg1, "start")
start = arg1
stop = arg2
else
internal.assert_not_nil(arg1, "stop")
start = 1
stop = arg1
end
end
iterator.curr = start
iterator.stop = stop
iterator.step = step
return iterator
end
--- Iterate over the function's returned values upon repeated calls.
-- <p>This can effectively convert a vanilla-Lua iterator into a capital I @{Iterator}.
-- For example, <code>Iterator.from(io.lines "my_file.txt")</code> gives you a
-- string iterator over the lines in a file.</p>
-- <p>In general, any expression you can use in a for loop, you can wrap into an <code>Iterator.from</code>
-- to get the same sequence of values in an @{Iterator} form. For more information on iterators,
-- read <a href="http://www.lua.org/pil/7.1.html">chapter 7 of Programming in Lua</a>.</p>
-- <p>Since any repeated function call without arguments can be used as a vanilla Lua iterator,
-- they can also be used with <code>Iterator.from</code>. For an example, see Usage.</p>
-- @usage
-- local i = 0
-- local function my_counter()
-- i = i + 1
-- if i > 10 then return nil end
-- return i
-- end
-- f.from(my_counter):foreach(print) -- prints 1 through 10 and stops
-- @tparam function func the function to call
-- @param is invariant state passed to <code>func</code>
-- @param var initial variable passed to <code>func</code>
-- @treturn Iterator the new <code>@{Iterator}</code>
-- @see Iterator.packed_from
function Iterator.from(func, is, var)
internal.assert_not_nil(func, "func")
local iterator = internal.base_iter(nil, internal.func_call_next, internal.func_try_clone)
iterator.func = func
iterator.is = is
iterator.var = var
return iterator
end
--- Iterate over the function's returned values (packed into a table) upon repeated calls.
-- This is similar to @{Iterator.from}, but instead of the created Iterator
-- generating multiple return values per call, it returns them all
-- packed into an array.
-- @tparam function func the function to call
-- @param is invariant state passed to <code>func</code>
-- @param var initial variable passed to <code>func</code>
-- @treturn Iterator the new <code>@{Iterator}</code>
-- @see Iterator.from
function Iterator.packed_from(func, is, var)
internal.assert_not_nil(func, "func")
local iterator = Iterator.from(func, is, var)
return iterator:map(internal.pack)
end
--- Iterate over the <code>coroutine</code>'s yielded values.
-- <p>For example, assume you have a coroutine that produces messages from
-- clients. One easy way to consume them in a for loop would be as in Usage.</p>
-- @tparam thread co the <code>coroutine</code> to iterate
-- @treturn Iterator the new <code>@{Iterator}</code>
-- @usage
-- local function my_totally_real_message_queue()
-- coroutine.yield("this is a message")
-- coroutine.yield("hello!")
-- coroutine.yield("almost done")
-- coroutine.yield("bye bye")
-- end
--
-- local co = coroutine.create(my_totally_real_message_queue)
-- for count, message in f.Iterator.from_coroutine(co):enumerate() do
-- io.write(count, ": ", message, "\n")
-- end
-- io.write("end")
function Iterator.from_coroutine(co)
internal.assert_coroutine(co, "co")
return internal.wrap_coroutine(co)
end
--- Nondestructively return an independent iterable from the given one.
-- <p>If <code>iterable</code> is an Iterator, clone it according
-- to its subtype. If <code>iterable</code> is an array, then
-- return itself.</p>
-- <p>Please note that coroutine and iterated function call iterators
-- cannot be cloned.</p>
-- @tparam iterable iterable the iterable to be cloned
-- @treturn iterable the clone
function Iterator.clone(iterable)
internal.assert_not_nil(iterable, "iterable")
if internal.is_iterator(iterable) then
return iterable:clone()
else
return iterable
end
end
--- Select only values which match the predicate.
-- @tparam predicate predicate the function to evaluate for each value
-- @treturn Iterator the filtering <code>@{Iterator}</code>
function Iterator:filter(predicate)
internal.assert_not_nil(predicate, "predicate")
local iterator = internal.base_iter(self, internal.filter_next, internal.filter_clone)
iterator.predicate = predicate
return iterator
end
--- Map values into new values.
-- <p>Please note that at no point during iteration may
-- the <code>mapping</code> function return <code>nil</code>
-- as its first value.</p>
-- @tparam function mapping the function to evaluate for each value
-- @treturn Iterator the mapping <code>@{Iterator}</code>
function Iterator:map(mapping)
internal.assert_not_nil(mapping, "mapping")
local iterator = internal.base_iter(self, internal.map_next, internal.map_clone)
iterator.mapping = M.compose(internal.func_nil_guard, mapping)
return iterator
end
--- Collapse values into a single value.
-- <p>A reducer is a function of the form
-- <pre>function(accumulated_value, new_value)</pre>
-- which returns the reducing or "accumulation" of
-- <code>accumulated_value</code> and <code>new_value</code></p>
-- <p>The definition of "reducing" is flexible, and a few common examples
-- include sum and concatenation.</p>
-- @tparam reducer reducer the collapsing function
-- @param initial_value the initial value passed to the <code>reducer</code>
-- @return the accumulation of all values
function Iterator:reduce(reducer, initial_value)
internal.assert_not_nil(reducer, "reducer")
local reduced_result = initial_value
local function reduce(next_value)
reduced_result = reducer(reduced_result, next_value)
end
self:foreach(reduce)
return reduced_result
end
--- Apply a function to all values.
-- <p>The main difference between <code>@{Iterator:foreach}</code> and
-- <code>@{Iterator:map}</code> is that <code>foreach</code> ignores the
-- return value(s) of its function, while map uses them and has restrictions
-- on what it can return.</p>
-- <p>Another important difference is that <code>@{Iterator:map}</code>
-- is a lazy evaluator, while <code>@{Iterator:foreach}</code> iterates over
-- its values immediately.</p>
-- @tparam function func the function to apply for each value
function Iterator:foreach(func)
internal.assert_not_nil(func, "func")
local next_input = {self:next()}
while not self:is_complete() do
func(unpack(next_input))
next_input = {self:next()}
end
end
--- Consume the iterator and retrieve the last value it produces.
-- @return the last value produced by the iterator, or <code>nil</code> if there was none.
function Iterator:last()
local last
local buffer
repeat
last = buffer
buffer = self:next()
until buffer == nil
return last
end
--- Iterate over the <code>n</code> first values and stop.
-- @tparam integer n amount of values to take
-- @treturn Iterator the new <code>@{Iterator}</code>
function Iterator:take(n)
internal.assert_integer(n, "n")
local iterator = internal.base_iter(self, internal.take_next, internal.take_clone)
iterator.n_remaining = n
return iterator
end
--- Iterate while <code>predicate</code> is <code>true</code> and stop.
-- @tparam predicate predicate the predicate to check against
-- @treturn Iterator the new <code>@{Iterator}</code>
function Iterator:take_while(predicate)
internal.assert_not_nil(predicate, "predicate")
local iterator = internal.base_iter(self, internal.take_while_next, internal.take_while_clone)
iterator.predicate = predicate
iterator.done_taking = false
return iterator
end
--- Consume the iterator and produce its <code>n</code> last values in order.
-- @tparam integer n the number of elements to capture
-- @treturn Iterator the new <code>@{Iterator}</code> which will produce said values
function Iterator:take_last(n)
internal.assert_integer(n, "n")
local iterator = internal.base_iter(self, internal.take_last_next, internal.take_last_clone)
iterator.buffer = {}
iterator.n = n
iterator.index = 1
iterator.consumed_source = false
return iterator
end
--- Iterate while <code>predicate</code> is <code>false</code> and stop.
-- @tparam predicate predicate the predicate to check against
-- @treturn Iterator the new <code>@{Iterator}</code>
function Iterator:take_until(predicate)
return self:take_while(M.negate(predicate))
end
--- Iterate over the values, starting at the <code>(n+1)</code>th one.
-- @tparam integer n amount of values to skip
-- @treturn Iterator the new <code>@{Iterator}</code>
function Iterator:skip(n)
internal.assert_integer(n, "n")
local iterator = internal.base_iter(self, internal.skip_next, internal.skip_clone)
iterator.n_remaining = n
return iterator
end
--- Iterate over the values, starting whenever <code>predicate</code> becomes <code>false</code> for the first time.
-- @tparam predicate predicate the predicate to check against
-- @treturn Iterator the new <code>@{Iterator}</code>
function Iterator:skip_while(predicate)
internal.assert_not_nil(predicate, "predicate")
local iterator = internal.base_iter(self, internal.skip_while_next, internal.skip_while_clone)
iterator.predicate = predicate
iterator.done_skipping = false
return iterator
end
--- Iterate over the values, starting whenever <code>predicate</code> becomes <code>true</code> for the first time.
-- @tparam predicate predicate the predicate to check against
-- @treturn Iterator the new <code>@{Iterator}</code>
function Iterator:skip_until(predicate)
return self:skip_while(M.negate(predicate))
end
--- Take 1 value every <code>n</code>.
-- <p>The first value is always taken.</p>
-- @tparam integer n one more than the number of skipped values
-- @treturn Iterator the new <code>@{Iterator}</code>
-- @see Iterator:skip
function Iterator:every(n)
internal.assert_integer(n, "n")
local iterator = internal.base_iter(self, internal.every_next, internal.every_clone)
iterator.n = n
iterator.first_call = true
return iterator
end
--- Checks if any values evaluate to <code>true</code>.
-- @tparam predicate predicate the function to evaluate for each value,
-- defaults to <pre>not (value == nil or value == false)</pre>
-- @treturn boolean <code>true</code> if and only if at least one of the
-- values evaluate to <code>true</code>
function Iterator:any(predicate)
if predicate then
return self:map(predicate):any()
else
for value in self do
if value then
return true
end
end
return false
end
end
--- Checks if all values evaluate to <code>true</code>.
-- @tparam predicate predicate the function to evaluate for each value,
-- defaults to <pre>not (value == nil or value == false)</pre>
-- @treturn boolean <code>true</code> if and only if all of the
-- values evaluate to <code>true</code>
function Iterator:all(predicate)
if predicate then
return self:map(predicate):all()
else
for value in self do
if not value then
return false
end
end
return true
end
end
--- Counts how many values evaluate to <code>true</code>.
-- @tparam predicate predicate function to evaluate for each value; if
-- <code>nil</code>, then counts all values.
-- @treturn integer the number of values that match the <code>predicate</code>
function Iterator:count(predicate)
if not predicate then
predicate = M.constant(true)
end
local c = 0
for e in self do
if predicate(e) then
c = c + 1
end
end
return c
end
--- Iterate over two iterables simultaneously.
-- <p>This results in an Iterator with multiple values per :next() call.</p>
-- <p>The new Iterator will be considered complete as soon as the one the method
-- was called on (<code>self</code>) is completed, regardless of the status of <code>other</code>.</p>
-- @tparam iterable other the other iterable to zip with this one
-- @treturn Iterator the resulting zipped Iterator
function Iterator:zip(other)
other = exports.iterate(other)
local iterator = internal.base_iter({self, other}, internal.zip_next, internal.zip_clone)
return iterator
end
--- Iterate over two iterables simultaneously, giving their values as an array.
-- <p>This results in an Iterator with a single value per :next() call.</p>
-- @tparam iterable other the other iterable to zip with this one
-- @treturn Iterator the resulting zipped Iterator
function Iterator:packed_zip(other)
return self:zip(other):map(internal.pack)
end
--- Include an index while iterating.
-- <p>The index is given as a single value to the left of all return values. Otherwise,
-- the iterator is unchanged. This is similar to how <code>ipairs</code> iterates over
-- an array, except it can be used with any iterator.</p>
-- @treturn Iterator the resulting indexed Iterator
-- @see enumerate
-- @usage
-- letters = f.every({"a", "b", "c", "d", "e"}, 2)
-- for idx, letter in letters:enumerate() do
-- print(idx, letter)
-- end
function Iterator:enumerate()
local iterator = internal.base_iter(self, internal.enumerate_next, internal.enumerate_clone)
iterator.index = 0
return iterator
end
--- Append elements from <code>other</code> after this iterator has been exhausted.
-- @tparam iterable other the iterator whose elements will be appended
-- @treturn Iterator the concatenation
function Iterator:concat(other)
other = exports.iterate(other)
local iterator = internal.base_iter({self, other}, internal.concat_next, internal.concat_clone)
return iterator
end
--- Create an array out of the <code>@{Iterator}</code>'s values.
-- @treturn array the array of values
function Iterator:to_array()
local array = {}
self:foreach(M.bind(table.insert, array))
return array
end
--- Create a <code>coroutine</code> that yields the values.
-- of the <code>@{Iterator}</code>.
-- @treturn thread The new <code>coroutine</code>
function Iterator:to_coroutine()
return coroutine.create(internal.coroutine_iter_loop(self))
end
--- Check whether or not the iterator is done.
-- <p>Please note that even if the iterator has reached its actual last
-- value, it has no way of knowing it was the last. Therefore, this function
-- will only return true once the iterator returns <code>nil</code> for the
-- first time.</p>
-- @treturn boolean <code>true</code> if the <code>@{Iterator}</code>
-- has iterated over all its values.
function Iterator:is_complete()
return self.completed
end
--- @section end
-- RAW FUNCTIONS --
--- Create an <code>@{Iterator}</code> for the <code>iterable</code>.
-- <p>Equivalent to <pre>Iterator.over(iterable)</pre>.</p>
-- @tparam iterable iterable the values to be iterated over
-- @treturn Iterator the new <code>@{Iterator}</code>
-- @function iterate
function exports.iterate(iterable)
return Iterator.over(iterable)
end
--- Iterate over the naturals starting at 1.
-- @treturn Iterator the counter
-- @see Iterator:take
-- @see Iterator:skip
-- @see Iterator:every
-- @function counter
function exports.counter()
return Iterator.counter()
end
--- Create an integer iterator that goes from <code>start</code> to <code>stop</code>, <code>step</code>-wise.
-- @tparam[opt=1] integer start the start of the integer range
-- @tparam integer stop the end of the integer range (inclusive)
-- @tparam[opt=1] integer step the difference between consecutive elements
-- @treturn Iterator the new <code>@{Iterator}</code>
-- @function range
-- @see Iterator.range
function exports.range(...)
return Iterator.range(...)
end
--- Select only values which match the predicate.
-- <p>Equivalent to <pre>iterate(iterable):filter(predicate)</pre>.</p>
-- @tparam iterable iterable the values to be filtered
-- @tparam predicate predicate the function to evaluate for each value
-- @treturn Iterator the filtering <code>@{Iterator}</code>
-- @see iterate
-- @see Iterator:filter
-- @function filter
function exports.filter(iterable, predicate)
return exports.iterate(iterable):filter(predicate)
end
--- Map values into new values.
-- <p>Equivalent to <pre>iterate(iterable):map(mapping)</pre>.</p>
-- <p>Please note that at no point during iteration may
-- the <code>mapping</code> function return <code>nil</code>
-- as its first value.</p>
-- @tparam iterable iterable the values to be mapped
-- @tparam function mapping the function to evaluate for each value
-- @treturn Iterator the mapping <code>@{Iterator}</code>
-- @see iterate
-- @see Iterator:map
-- @function map
function exports.map(iterable, mapping)
return exports.iterate(iterable):map(mapping)
end
--- Collapse values into a single value.
-- <p>Equivalent to <pre>iterate(iterable):reduce(reducer, initial_value)</pre>.</p>
-- <p>A reducer is a function of the form
-- <pre>function(accumulated_value, new_value)</pre>
-- which returns the reducing or "accumulation" of
-- <code>accumulated_value</code> and <code>new_value</code></p>
-- <p>The definition of "reducing" is flexible, and a few common examples
-- include sum and concatenation.</p>
-- @tparam iterable iterable the values to be collapsed
-- @tparam reducer reducer the collapsing function
-- @param initial_value the initial value passed to the <code>reducer</code>
-- @return the accumulation of all values
-- @see iterate
-- @see Iterator:reduce
-- @function reduce
function exports.reduce(iterable, reducer, initial_value)
return exports.iterate(iterable):reduce(reducer, initial_value)
end
--- Apply a function to all values.
-- <p>Equivalent to <pre>iterate(iterable):foreach(func)</pre>.</p>
-- <p>The main difference between <code>@{foreach}</code> and
-- <code>@{map}</code> is that <code>foreach</code> ignores the
-- return value(s) of its function, while map uses them and has restrictions
-- on what it can return.</p>
-- <p>Another important difference is that <code>@{map}</code>
-- is a lazy evaluator, while <code>@{foreach}</code> iterates over
-- its values immediately.</p>
-- @tparam iterable iterable the values to be iterated over
-- @tparam function func the function to apply for each value
-- @see iterate
-- @see Iterator:foreach
-- @function foreach
function exports.foreach(iterable, func)
return exports.iterate(iterable):foreach(func)
end
--- Return the last value of the given iterable.
-- <p>If <code>iterable</code> is an iterator, this call is equivalent to <code>iterable:last()</code>.
-- Otherwise, this call accesses the last element in the array.</p>
-- @tparam iterable iterable the sequence whose last element is to be accessed
-- @return the last element in the sequence
-- @see Iterator:last
-- @function last
function M.last(iterable)
if internal.is_iterator(iterable) then
return iterable:last()
else
return iterable[#iterable]
end
end
--- Iterate over the <code>n</code> first values and stop.
-- <p>Equivalent to <pre>iterate(iterable):take(n)</pre>.</p>
-- @tparam iterable iterable the values to be iterated over
-- @tparam integer n amount of values to take
-- @treturn Iterator the new <code>@{Iterator}</code>
-- @see iterate
-- @see Iterator:take
-- @function take
function exports.take(iterable, n)
return exports.iterate(iterable):take(n)
end
--- Iterate over the values, starting at the <code>(n+1)</code>th one.
-- <p>Equivalent to <pre>iterate(iterable):skip(n)</pre>.</p>
-- @tparam iterable iterable the values to be iterated over
-- @tparam integer n amount of values to skip
-- @treturn Iterator the new <code>@{Iterator}</code>
-- @see iterate
-- @see Iterator:skip
-- @function skip
function exports.skip(iterable, n)
return exports.iterate(iterable):skip(n)
end
--- Take 1 value every <code>n</code>.
-- <p>Equivalent to <pre>iterate(iterable):every(n)</pre>.</p>
-- <p>The first value is always taken.</p>
-- @tparam iterable iterable the values to be iterated over
-- @tparam integer n one more than the number of skipped values
-- @treturn Iterator the new <code>@{Iterator}</code>
-- @see Iterator:every
-- @see iterate
-- @see skip
-- @function every
function exports.every(iterable, n)
return exports.iterate(iterable):every(n)
end
--- Checks if any values evaluate to <code>true</code>.
-- <p>Equivalent to <pre>iterate(iterable):any(predicate)</pre>.</p>
-- @tparam iterable iterable the values to be iterated over
-- @tparam predicate predicate the function to evaluate for each value,
-- defaults to <pre>not (value == nil or value == false)</pre>
-- @treturn boolean <code>true</code> if and only if at least one of the
-- values evaluate to <code>true</code>
-- @see Iterator:any
-- @see iterate
-- @function any
function exports.any(iterable, predicate)
return exports.iterate(iterable):any(predicate)
end
--- Checks if all values evaluate to <code>true</code>.
-- <p>Equivalent to <pre>iterate(iterable):all(predicate)</pre>.</p>
-- @tparam iterable iterable the values to be iterated over
-- @tparam predicate predicate the function to evaluate for each value,
-- defaults to <pre>not (value == nil or value == false)</pre>
-- @treturn boolean <code>true</code> if and only if all of the
-- values evaluate to <code>true</code>
-- @see Iterator:all
-- @see iterate
-- @function all
function exports.all(iterable, predicate)
return exports.iterate(iterable):all(predicate)
end
--- Iterate over two iterables simultaneously.
-- @see Iterator:zip
-- @function zip
function exports.zip(iter1, iter2)
return exports.iterate(iter1):zip(iter2)
end
--- Iterate over two iterables simultaneously.
-- @see Iterator:packed_zip
-- @function packed_zip
function exports.packed_zip(iter1, iter2)
return exports.iterate(iter1):packed_zip(iter2)
end
--- Iterate with an added index.
-- @see Iterator:enumerate
-- @function enumerate
function exports.enumerate(iter)
return exports.iterate(iter):enumerate()
end
--- Concatenate two iterables into an Iterator.
-- @see Iterator:concat
-- @function concat
function exports.concat(iter1, iter2)
return exports.iterate(iter1):concat(iter2)
end
--- Does nothing.
-- @function nop
function exports.nop()
end
--- Returns its arguments in the same order.
-- @param ... the values to be returned
-- @return the given values
-- @function identity
function exports.identity(...)
return ...
end
--- Create a lambda function from a given definition string.
-- <p><em>DO NOT USE THIS WITH UNTRUSTED AND/OR UNKNOWN STRINGS!</em></p>
-- <p>This and @{clambda} are meant to facilitate the creation of inline
-- functions, given the vanilla Lua syntax is quite verbose (especially with
-- higher order functions).</p>
-- <p>To attempt limit user error and naïve attacks, some restrictions are put
-- in place with respect to the definition:</p>
-- <ul>
-- <li>It must be of the form <code>(arglist) => body</code>, where
-- <code>body</code> is either another lambda definition or an expression that
-- could normally be put inside parenthesis in Lua.</li>
-- <li>The <code>()=></code> chain must not be longer than 10 steps.</li>
-- <li>The environment <code>env</code> must not contain more than 150 string keys.</li>
-- <li>The definition string must not be longer than 100 bytes.</li>
-- <li>The definition string must not contain a newline ("<code>\n</code>") character.</li>
-- <li>The definition string must not contain the substring "<code>--</code>".</li>
-- <li>The definition string must not contain the word "<code>end</code>".</li>
-- </ul>
-- @usage
-- local add = f.lambda "(x, y) => x + y"
-- print(add(2, 3)) --> 5
-- local emphasis = f.lambda("(x)=>x..suffix", {suffix = "!!"})
-- -- f.lambda can even create higher order functions easily
-- local linear_combinator = f.lambda "(m) => (x, y) => m*x + y"
-- local comb2 = linear_combinator(2)
-- print(comb2(3, 4)) --> 10
-- -- lambdas can "see" variables given in their environment
-- local emphasis = f.lambda("(x)=>x..suffix", {suffix = "!!"})
-- emphasis = f.lambda{"(x)=>x..suffix", suffix = "!!"} -- alternative way to define environment
-- print(emphasis("Hello")) --> Hello!!
-- @tparam string|table lambda_def the definition to be made into a function
-- @tparam[opt={}] table env the function environment
-- @treturn function the generated function
-- @see clambda
-- @function lambda
function exports.lambda(lambda_def, env, token)
-- token is for internal use only
local calling_from_clambda = (token == internal.proof_clambda_call)
local err_level = calling_from_clambda and 3 or 2
assert(load or loadstring) -- sanity check
if type(lambda_def) == "table" then
lambda_def, env = lambda_def[1], lambda_def
env[1] = nil
end
lambda_def, env = internal.sanitize_lambda(lambda_def, env, err_level)
local lambda_lines = internal.expand_lambda(lambda_def, 1, "")
local lambda_body = table.concat(lambda_lines, "\n")
local ctx = debug.getinfo(err_level, "nSl")
local chunk_name = ("lambda(%s:%s)"):format(ctx.source, ctx.currentline)
local chunk
if loadstring then
-- Lua 5.1 and LuaJIT support
chunk = loadstring(lambda_body, chunk_name)
else
chunk = load(lambda_body, chunk_name, "t", env)
end
if not chunk then
error("Load failed for lambda:\n" .. lambda_body, err_level)
end
local f = chunk()
if setfenv then
setfenv(f, env)
end
local lbd = {}
lbd.func = f
lbd.expr = lambda_def
lbd.body = lambda_body:match "^return%s*(.*)$"
setmetatable(lbd, lambda_function__meta)
return lbd
end
--- Create a context-aware lambda function.
-- <p><em>DO NOT USE THIS WITH UNTRUSTED AND/OR UNKNOWN STRINGS!</em></p>
-- <p>This works similarly to @{lambda}, except it automatically adds
-- any globals and locals visible to the calling context into its environment.</p>
-- <p>See @{lambda} for more information on restrictions and usage.</p>
-- @usage
-- local angle = math.pi / 3
-- local offset_sin = f.clambda "(x) => math.sin(x + angle)"
-- print(offset_sin(math.pi)) --> -0.866
-- print(offset_sin(2 * math.pi / 3)) --> 0
-- local alternative = f.clambda("(x)=>sin(x + angle)", {sin=math.sin})
-- local or_even = f.clambda{"(x)=>sin(x+angle)", sin=math.sin}
-- @tparam string|table expr the expression to be made into a function
-- @tparam table extra_env additional values to insert into the environment
-- @see lambda
-- @function clambda
function exports.clambda(expr, extra_env)
if type(expr) == "table" then
expr, extra_env = expr[1], expr
extra_env[1] = nil
end
local env = {}
internal.merge_env(env, _G)
internal.merge_env(env, internal.get_locals(2))
internal.merge_env(env, extra_env or {})
return exports.lambda(expr, env, internal.proof_clambda_call)
end
internal.proof_clambda_call = {}
--- Create a lambda function from a given expression string.
-- <p><em>DO NOT USE THIS WITH UNTRUSTED OR UNKNOWN STRINGS!</em></p>
-- <p>This is meant to facilitate writing inline functions, since
-- the vanilla Lua way is very verbose.</p>
-- <p>The expression must abide by several criteria:</p>
-- <ul>
-- <li>It <em>must</em> be an expression that would make sense if put inside parenthesis in vanilla Lua;
-- <li>It <em>must not</em> start with the word "return";
-- <li>It <em>must not</em> contain any newlines (if you need multiple lines, it shouldn't be a lambda);
-- <li>It <em>must not</em> contain comments, or the sequence <code>--</code> inside strings;
-- <li>It <em>must not</em> contain the words "end" or "_ENV", <em>even inside strings</em>.
-- </ul>
-- <p>If any of the above criteria fail to be met, the lambda creator will error.</p>
-- <p>Even with these measures, it is still not safe to create lambdas from untrusted sources.
-- These are attempts to prevent the most basic and naïve attacks, as well as mistakes on the part
-- of the programmer.</p>
-- <p>Inside the expression, the names <code>_1</code>, <code>_2</code>, <code>_3</code>, <code>_4</code>,
-- <code>_5</code>, <code>_6</code>, <code>_7</code>, <code>_8</code>, and <code>_9</code> can be used
-- to refer to the arguments given to the function. Alternatively, the letters <code>a</code> through
-- <code>i</code> can also be used. For the first 3 arguments, an additional alias exists: <code>x</code>,
-- <code>y</code>, and <code>z</code>. And lastly, for the first argument, simply <code>_</code> or <code>v</code> may be used.</p>
-- <p>The lambda function is isolated into a sandboxed environment. That means it cannot read or write
-- to local or global variables. If the function must access variables that are not given as arguments,
-- you must add them to the <code>env</code> table. Setting a key <code>k</code> of that table to a
-- value <code>v</code> will provide the given lambda with a variable called <code>k</code>
-- with value <code>v</code>.</p>
-- <p>When using <code>env</code> to overwrite the parameter name aliases (i.e., <code>a-i</code>,
-- <code>x-z</code>, and <code>v</code>), it is important that the new value is neither <code>nil</code> nor <code>false</code>.
-- Due to the internal mechanism used to detect when to set these aliases, having a falsy value counts
-- as not being defined. In order to minimize debugging and frustration in this niche use case of <code>env</code>,
-- the lambda will not be created and instead it will error stating which alias would fail to be set.</p>
-- <p>For convenience, it is also allowed to call <code>lambda</code> with a single table as an argument. This table
-- must contain the lambda expression in index <code>1</code>, and all other keys are interpreted as part of its
-- environment.</p>
-- <p>Examples:</p>
-- <ul>
-- <li> <code>add = f.lambda "_1 + _2" -- adds its 2 arguments</code>
-- <li> <code>add = f.lambda "a + b" -- same as above</code>
-- <li> <code>add = f.lambda "x + y" -- same as above</code>
-- <li> <code>inc = f.lambda "_1 + 1" -- adds 1 to its argument</code>
-- <li> <code>inc = f.lambda "a + 1" -- same as above</code>
-- <li> <code>inc = f.lambda "x + 1" -- same as above</code>
-- <li> <code>inc = f.lambda "_ + 1" -- same as above</code>
-- <li> <code>double_plus_one = f.lambda("_ + inc(_)", {inc = inc}) -- lets lambda "see" inc exists</code>
-- <li> <code>double_plus_one = f.lambda{"_ + inc(_)", inc = inc} -- this is also a valid way to call it</code>
-- <li> <code>valid_env = f.lambda("v + 2*i", {i = complex.i}) -- defines i as complex.i instead of an alias for _9</code>
-- <li> <code>valid_env = f.lambda{"v + 2*i", i = complex.i} -- also valid</code>
-- <li> <code>invalid_env = f.lambda("v and not f", {f = false}) -- ERROR! f cannot be assigned a falsy value because it's an alias for _6</code>
-- </ul>
-- @tparam string expr the expression to be made into a function
-- @tparam[opt={}] table env the function environment
-- @treturn function the generated function
-- @see clambda
local function lambda_old(expr, env)
-- Just making sure I didn't forget any major version
assert(load or loadstring)
if type(expr) == "table" then
expr, env = expr[1], expr
env[1] = nil
end
expr, env = internal.sanitize_lambda(expr, env)
local body = [[
return function(_1, _2, _3, _4, _5, _6, _7, _8, _9)
local _, x, a, v = _1, x or _1, a or _1, v or _1
local y, b = y or _2, b or _2
local z, c = z or _3, c or _3
local d, e, f, g, h, i = d or _4, e or _5, f or _6, g or _7, h or _8, i or _9
return ]] .. expr .. [[ -- This comment is here to force a newline
end]]
-- Get context that created lambda for debug purposes
local ctx = debug.getinfo(2, "nSl")
local chunk_name = ("lambda(%s:%s)"):format(
ctx.source, -- file name
ctx.currentline
)
local chunk
if loadstring then
-- Lua 5.1 and LuaJIT support
chunk = loadstring(body, chunk_name)
else
chunk = load(body, chunk_name, "t", env)
end
if not chunk then
error("Load failed for lambda body: " .. expr, 2)
end
local f = chunk()
-- Lua 5.1 and LuaJIT support
if setfenv then
setfenv(f, env)
end
local lbd = {}
lbd.func = f
lbd.expr = expr
setmetatable(lbd, lambda_function__meta)
return lbd
end
function internal.indent_str(levels)
return (" "):rep(levels)
end
-- syntax: (optional arguments) => <anything>
function internal.lambda_split_params(def)
local arrow_after_parens = def:find "^%s*%([^%)]*%)%s*=>%s*"
if not arrow_after_parens then
-- just the lambda body
return nil, def
end
local arrow_start, arrow_end = def:find "%s*=>%s*"
local before_arrow = def:sub(1, arrow_start-1)
local body = def:sub(arrow_end+1)
local _, param_list_start = before_arrow:find "^%s*%("
local param_list = before_arrow:match("%(([%w%s,]*)%)", param_list_start)
return param_list, body
end