-
Notifications
You must be signed in to change notification settings - Fork 2
/
Functional.mon
1489 lines (1348 loc) · 53.9 KB
/
Functional.mon
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
package com.apamax.functional;
/** @private */
event Util
{
// Returns the return type of func if it's an action, or calls getFuncReturnType if it has that action
static action getFuncReturnType(any func) returns string
{
if func.hasAction("getFuncReturnType") {
return (<action<> returns string> func.getAction("getFuncReturnType"))();
}
return func.getActionReturnTypeName();
}
// if func has an execGeneric or generate action, return that, otherwise convert an action into the generic version
static action getGenericAction(any func) returns action<sequence<any>> returns any
{
if func.hasAction("execGeneric") {
return <action<sequence<any>> returns any> func.getAction("execGeneric");
} else if func.hasAction("generate") {
return func.getAction("generate").getGenericAction();
}
switch (func) {
case action<sequence<any>> returns any: {
return func;
}
default: {
return func.getGenericAction();
}
}
}
// if func has a getNumberOfArgs action call it, otherwise call getActionParameterTypeNames
static action getNumberOfArgs(any func) returns integer
{
if func.hasAction("getNumberOfArgs") {
return (<action<> returns integer> func.getAction("getNumberOfArgs"))();
}
return func.getActionParameterTypeNames().size();
}
/** Convert value(s) of arg to a sequence<any> containing the value(s).
If arg is not a sequence, create the sequence and put the value in it.
If arg is already a sequence, copy the values from the sequence.
*/
static action getGenericSequence(any arg) returns sequence<any> {
if arg.empty() {
return new sequence<any>;
} else if arg.getTypeName().find("sequence<") = 0 { // already a sequence?
return arg.getEntries();
} else {
return [arg];
}
}
/** Return a new default instance of the return type of the function.
*/
static action returnTypeInstanceOf(any func) returns any {
return any.newInstance(getFuncReturnType(func));
}
}
/**
Represents a generator over a function. This class is used internally by Functional, but you can use any event with a generate method.
Generate methods must take 0 arguments and can return the type of your choice (or any).
*/
event Generator
{
/** @private */
static action create(any start, any func) returns Generator
{
Generator g := new Generator;
g.accumulator := start;
g.func := Util.getGenericAction(func);
g.retType := Util.getFuncReturnType(func);
g.args := [g.accumulator];
return g;
}
/** @private */
action getFuncReturnType() returns string { return retType; }
/**
Returns the next item from this generator.
@returns The next item.
*/
action generate() returns any
{
args[0] := accumulator;
accumulator := func(args);
return accumulator;
}
/** @private */
any accumulator;
/** @private */
action<sequence<any>> returns any func;
/** @private */
sequence<any> args;
/** @private */
string retType;
}
/** @private */
event GenerateIf
{
// Create the GenerateIf
static action create(action<sequence<any>> returns any wrapped, action<sequence<any>> returns any predicate, string retType) returns GenerateIf
{
GenerateIf gi := new GenerateIf;
gi.wrapped := wrapped;
gi.predicate := predicate;
gi.wrappedargs := new sequence<any>;
gi.args := [new any];
gi.retType := retType;
return gi;
}
// Just call the underlying generator until the predicate returns true for it
action generate(any _) returns any
{
while true {
any candidate := wrapped(wrappedargs);
args[0] := candidate;
if <boolean> predicate(args) {
return candidate;
}
}
return new any; // never happens
}
action getFuncReturnType() returns string { return retType; }
action<sequence<any>> returns any wrapped;
action<sequence<any>> returns any predicate;
sequence<any> wrappedargs;
sequence<any> args;
string retType;
}
/** @private */
event GenerateWrap
{
// Create the GenerateWrap
static action create(action<sequence<any>> returns any wrapped, action<sequence<any>> returns any func, string retType) returns GenerateWrap
{
GenerateWrap gw := new GenerateWrap;
gw.wrapped := wrapped;
gw.func := func;
gw.wrappedargs := new sequence<any>;
gw.args := [new any];
gw.retType := retType;
return gw;
}
// Call the underlying generator, then call func on it and return the result
action generate(any _) returns any
{
args[0] := wrapped(wrappedargs);
return func(args);
}
action getFuncReturnType() returns string { return retType; }
action<sequence<any>> returns any wrapped;
action<sequence<any>> returns any func;
sequence<any> wrappedargs;
sequence<any> args;
string retType;
}
/** @private */
event AccumulateGenerator
{
// create the AccumulateGenerator with a default start
static action create(any container, any func) returns AccumulateGenerator
{
return createFrom(Util.returnTypeInstanceOf(func), container, func);
}
// create the AccumulateGenerator from a given start
static action createFrom(any start, any container, any func) returns AccumulateGenerator
{
AccumulateGenerator ag := new AccumulateGenerator;
ag.container := container;
ag.func := Util.getGenericAction(func);
ag.acc := start;
ag.retType := Util.getFuncReturnType(func);
string tn := container.getTypeName();
if tn.find("sequence<") = 0 {
ag.index := 0;
} else if container.hasAction("generate") {
/*action<sequence<any>> returns any act := container.getAction("generate").getGenericAction();
any foo := <action<sequence<any>> returns any> act;
foo := <action<sequence<any>> returns any> ag.index;*/
ag.index := container.getAction("generate");
} else {
throw com.apama.exceptions.Exception("Can only accumulate over sequence or generator types", "typeException");
}
ag.args := [new any, new any];
return ag;
}
// call the underlying generator, or the next item in the sequence, and then the accumulate function with that, and return the current accumulator
action generate(any _) returns any
{
any value := new any;
switch(index) {
/*case action<sequence<any>> returns any: {
// it's a generator
value := index(args);
}*/
case integer: {
// it's a sequence
if not container.hasEntry(index) { return new any; }
value := container.getEntry(index);
self.index := index + 1;
}
default: {
value := index.getGenericAction()(new sequence<any>);
}
}
args[0] := acc;
args[1] := value;
acc := func(args);
return acc;
}
action getFuncReturnType() returns string { return retType; }
any container;
action<sequence<any>> returns any func;
sequence<any> args;
any acc;
any index;
string retType;
}
/** @private */
event RandomGenerator
{
// create a random generator with the given limit
static action create(any limit) returns RandomGenerator
{
return RandomGenerator(limit, limit.getAction("rand").getGenericAction(), new sequence<any>);
}
action generate(any _) returns any
{
return randfn(emptysequence);
}
action getFuncReturnType() returns string
{
return limit.getTypeName();
}
any limit;
action<sequence<any>> returns any randfn;
sequence<any> emptysequence;
}
/** @private */
event ArgMapGenerator
{
// create the ArgMapGenerator
static action create(action<sequence<any>> returns any source, any func) returns ArgMapGenerator
{
ArgMapGenerator ag := new ArgMapGenerator;
ag.func := Util.getGenericAction(func);
ag.retType := Util.getFuncReturnType(func);
ag.source := source;
ag.args := new sequence<any>;
return ag;
}
// Call the generator once, then call func with the result and return that
action generate(any _) returns any
{
any args := source(self.args);
return func(args.getEntries());
}
action getFuncReturnType() returns string { return retType; }
action<sequence<any>> returns any func;
action<sequence<any>> returns any source;
sequence<any> args;
string retType;
}
/** @private */
event SequenceCycleGenerator
{
// Create the SequenceCycleGenerator
static action create(any seq) returns SequenceCycleGenerator
{
SequenceCycleGenerator sg := new SequenceCycleGenerator;
sg.seq := seq;
sg.seqsize := (<action<> returns integer> seq.getAction("size"))();
sg.index := 0;
sg.retType := seq.getTypeName().substring(9,-1);
return sg;
}
// Return the next item in the sequence
action generate(any _) returns any
{
any value := seq.getEntry(index);
index := index + 1;
if index >= seqsize { index := 0; }
return value;
}
action getFuncReturnType() returns string { return retType; }
any seq;
integer index;
integer seqsize;
string retType;
}
/** @private */
event NotPred
{
// Create the NotPred
static action create(any pred) returns NotPred
{
NotPred np := new NotPred;
np.pred := Util.getGenericAction(pred);
np.args := [new any];
return np;
}
action<sequence<any>> returns any pred;
sequence<any> args;
// Call the predicate and invert the result
action execute(any i) returns boolean
{
args[0] := i;
return not <boolean> pred(args);
}
}
/** A partially evaluated function which can be passed to functional operators or later executed with the remaining arguments.
eg: <tt>Partial p := Fn.partial(concatFn, "Hello"); <string>p.exec(" world");</tt>
*/
event Partial
{
/** @private */
static action create(any arguments, any func) returns Partial
{
Partial p := new Partial;
p.args := Util.getGenericSequence(arguments);
p.curriedArgs := p.args.size();
p.func := Util.getGenericAction(func);
p.retType := Util.getFuncReturnType(func);
p.nArgs := Util.getNumberOfArgs(func)-p.args.size();
return p;
}
/** Take either an action, or a Partial and return a generic action version of either.
@param actionOrPartial Either an action or a Partial instance.
@return A generic action of a uniform type which either executes the action, or the curried Partial function.
*/
static action resolve(any actionOrPartial) returns action<sequence<any>> returns any
{
return Util.getGenericAction(actionOrPartial);
}
/** @private */
action getNumberOfArgs() returns integer { return nArgs; }
/** @private */
action getFuncReturnType() returns string { return retType; }
/** @private */
action execGeneric(sequence<any> args) returns any { return exec(args); }
/**
Execute the underlying function, passing in the remaining arguments.
@param args The remaining single argument, or sequence of all remaining arguments.
@return The result of executing the underlying function with the original and remaining arguments.
*/
action exec(any args) returns any
{
log "exec("+args.toString()+")" at CRIT;
sequence<any> _args;
if args.empty() { _args := new sequence<any>; }
else { _args := args.getEntries(); }
integer targetArgs := curriedArgs+_args.size();
if (self.args.size() != targetArgs) {
self.args.setSize(targetArgs);
}
integer i := curriedArgs;
any a;
for a in _args {
self.args[i] := a;
i := i + 1;
}
log "Calling func with "+self.args.toString() at CRIT;
return func(self.args);
}
/**
Add more partial arguments and return a new Partial which wraps this one.
@param args The additional single argument, or sequence of several additional arguments.
*/
action partial(any arguments) returns Partial
{
return Partial.create(arguments, self);
}
/** @private */
sequence<any> args;
/** @private */
integer curriedArgs;
/** @private */
action<sequence<any>> returns any func;
/** @private */
string retType;
/** @private */
integer nArgs;
}
/** @private */
event MeanFunctor
{
any sum;
integer count;
/** @private */
action mean(any acc, any i) returns any
{
switch (i) {
case integer: {
if sum.empty() { sum := 0; }
sum := <integer> sum + i;
count := count + 1;
return (<integer> sum) / count;
}
case float: {
if sum.empty() { sum := 0.; }
sum := <float> sum + i;
count := count + 1;
return (<float> sum) / count.toFloat();
}
case decimal: {
if sum.empty() { sum := 0.d; }
sum := <decimal> sum + i;
count := count + 1;
return (<decimal> sum) / count.toDecimal();
}
}
}
}
/**
Provides functional operations on EPL containers, such as map, reduce, filter and slice.
Also provides generators which can be used as input to the functional operations.
eg: <tt>Fn.slice(Fn.map(Fn.filter(Fn.count(), (integer i)->i%2=0), (integer i)->i*2), 2, 8, 2);</tt>
*/
event Fn
{
/**
Takes either a sequence, a dictionary or a generator and filters the contents using a boolean predicate func.
eg: <tt>Fn.filter(numbers, (integer i)->i%2=0)</tt>
Specifically, given:
<ul>
<li><tt>sequence<TYPE> container</tt> and <tt>action<TYPE> returns boolean func</tt> will return <tt>sequence<TYPE></tt> containing all the elements for which <tt>func</tt> returned true.</li>
<li><tt>dictionary<KEYTYPE,VALUETYPE> container</tt> and <tt>action<KEYTYPE,VALUETYPE> returns boolean func</tt> will return <tt>dictionary<KEYTYPE,VALUETYPE></tt> containing all the elements for which <tt>func</tt> returned true.</li>
<li>A generator returning <tt>TYPE</tt> and <tt>action<TYPE> returns boolean func</tt> will return a generator returning <tt>TYPE</tt> which only generates items from the original generator for which <tt>func</tt> returned true.</li>
</ul>
@param container A sequence, dictionary or generator.
@param func A boolean predicate function or lambda.
@returns The container filtered using the predicate function.
*/
static action filter(any container, any func) returns any
{
string tn := container.getTypeName();
any newcontainer := new any;
action<sequence<any>> returns any genericFunc := Util.getGenericAction(func);
if tn.find("sequence<") = 0 {
newcontainer := any.newInstance(tn);
action<integer> setsize := <action<integer>> newcontainer.getAction("setSize");
action<> returns integer getsize := <action<> returns integer> container.getAction("size");
setsize(getsize());
any value := new any;
integer index := 0;
sequence<any> args := [value];
for value in container.getEntries() {
args[0] := value;
if <boolean> genericFunc(args) {
newcontainer.setEntry(index, value);
index := index + 1;
}
}
setsize(index);
} else if tn.find("dictionary<") = 0 {
newcontainer := any.newInstance(tn);
integer nArgs := Util.getNumberOfArgs(func);
any key := new any;
sequence<any> args := [key];
for key in container.getKeys() {
any value := container.getEntry(key);
if (nArgs = 1) {
args[0] := value;
} else {
args.setSize(2);
args[0] := key;
args[1] := value;
}
if <boolean> genericFunc(args) {
newcontainer.setEntry(key, value);
}
}
} else if container.hasAction("generate") {
newcontainer := Generator.create(new any, GenerateIf.create(container.getAction("generate").getGenericAction(), genericFunc, Util.getFuncReturnType(container.getAction("generate"))));
} else {
throw com.apama.exceptions.Exception("Can only filter over container or generator types", "typeException");
}
return newcontainer;
}
/**
Takes either a sequence, a dictionary or a generator and maps the contents using a function.
eg: <tt>Fn.map(numbers, (integer i)->i*2)</tt>
Specifically, given:
<ul>
<li><tt>sequence<TYPEA> container</tt> and <tt>action<TYPEA> returns TYPEB func</tt> will return <tt>sequence<TYPEB></tt> containing the result of running <tt>func</tt> on all the elements in <tt>container</tt>.</li>
<li><tt>dictionary<KEYTYPE,VALUETYPEA> container</tt> and <tt>action<KEYTYPE,VALUETYPEA> returns VALUETYPEB func</tt> will return <tt>dictionary<KEYTYPE,VALUETYPEB></tt> containing the keys from <tt>container</tt> with the values being the result of running <tt>func</tt>.</li>
<li>A generator returning <tt>TYPEA</tt> and <tt>action<TYPEA> returns TYPEB func</tt> will return a generator returning <tt>TYPEB</tt> where each item is the corresponding item from the original generator after running <tt>func</tt>.</li>
</ul>
@param container A sequence, dictionary or generator.
@param func A function or lambda from old value type to new value type.
@returns The container with all the values run through func.
*/
static action map(any container, any func) returns any
{
string tn := container.getTypeName();
any newcontainer := new any;
action<sequence<any>> returns any genericFunc := Util.getGenericAction(func);
if tn.find("sequence<") = 0 {
newcontainer := any.newInstance("sequence<"+Util.getFuncReturnType(func)+">");
action<integer> setsize := <action<integer>> newcontainer.getAction("setSize");
action<> returns integer getsize := <action<> returns integer> container.getAction("size");
setsize(getsize());
any value := new any;
integer index := 0;
sequence<any> args := [value];
for value in container.getEntries() {
args[0] := value;
newcontainer.setEntry(index, genericFunc(args));
index := index + 1;
}
} else if tn.find("dictionary<") = 0 {
integer nArgs := Util.getNumberOfArgs(func);
newcontainer := any.newInstance("dictionary<"+container.getAction("hasKey").getActionParameterTypeNames()[0]+","+Util.getFuncReturnType(func)+">");
any key := new any;
sequence<any> args := [key];
for key in container.getKeys() {
any value := container.getEntry(key);
if (nArgs = 1) {
args[0] := value;
} else {
args.setSize(2);
args[0] := key;
args[1] := value;
}
newcontainer.setEntry(key, genericFunc(args));
}
} else if container.hasAction("generate") {
newcontainer := Generator.create(new any, GenerateWrap.create(container.getAction("generate").getGenericAction(), genericFunc, Util.getFuncReturnType(container.getAction("generate"))));
} else {
throw com.apama.exceptions.Exception("Can only map over container or generator types", "typeException");
}
return newcontainer;
}
/**
Takes either a sequence or a dictionary and accumulates all of the values using an accumulator function, returning the final result.
eg: <tt>Fn.reduce(numbers, (integer a, integer i)->a+i)</tt>
Specifically, given:
<ul>
<li><tt>sequence<TYPEA> container</tt> and <tt>action<TYPEB,TYPEA> returns TYPEB func</tt> will return the final <tt>TYPEB</tt> after calling <tt>func</tt> on each value, retaining <tt>TYPEB</tt> each time.</li>
<li><tt>dictionary<KEYTYPE,VALUETYPE> container</tt> and <tt>action<TYPEB,KEYTYPE,VALUETYPE> returns TYPEB func</tt> will return the final <tt>TYPEB</tt> after calling <tt>func</tt> on each key and value, retaining <tt>TYPEB</tt> each time.</li>
</ul>
@param container A sequence or dictionary.
@param func An accumulator function or lambda.
@returns The final result of the accumulator function.
*/
static action reduce(any container, any func) returns any
{
return reduceFrom(Util.returnTypeInstanceOf(func), container, func);
}
/**
Takes either a sequence or a dictionary and accumulates all of the values using an accumulator function, returning the final result.
eg: <tt>Fn.reduceFrom(42, numbers, (integer a, integer i)->a+i)</tt>
Specifically, given:
<ul>
<li><tt>sequence<TYPEA> container</tt> and <tt>action<TYPEB,TYPEA> returns TYPEB func</tt> will return the final <tt>TYPEB</tt> after calling <tt>func</tt> on each value, retaining <tt>TYPEB</tt> each time.</li>
<li><tt>dictionary<KEYTYPE,VALUETYPE> container</tt> and <tt>action<TYPEB,KEYTYPE,VALUETYPE> returns TYPEB func</tt> will return the final <tt>TYPEB</tt> after calling <tt>func</tt> on each key and value, retaining <tt>TYPEB</tt> each time.</li>
</ul>
@param accumulator initial value, of <tt>TYPEB</tt>
@param container A sequence or dictionary.
@param func An accumulator function or lambda.
@returns The final result of the accumulator function.
*/
static action reduceFrom(any accumulator, any container, any func) returns any
{
string tn := container.getTypeName();
action<sequence<any>> returns any genericFunc := Util.getGenericAction(func);
if tn.find("sequence<") = 0 {
any value := new any;
sequence<any> args := [accumulator, value];
for value in container.getEntries() {
args[0] := accumulator;
args[1] := value;
accumulator := genericFunc(args);
}
} else if tn.find("dictionary<") = 0 {
integer nArgs := Util.getNumberOfArgs(func);
any key := new any;
sequence<any> args := [accumulator, key];
sequence<any> keys := container.getKeys();
keys.sort();
for key in keys {
any value := container.getEntry(key);
if nArgs = 3 {
args.setSize(3);
args[0] := accumulator;
args[1] := key;
args[2] := value;
} else {
args[0] := accumulator;
args[1] := value;
}
accumulator := genericFunc(args);
}
} else {
throw com.apama.exceptions.Exception("Can only reduce over container or generator types", "typeException");
}
return accumulator;
}
/**
Takes either a sequence or a generator and returns a given sub-range as a finite sequence. If it is passed a generator, it will invoke the generator sufficient times immediately to satisfy the slice.
eg: <tt>Fn.slice(numbers, 5, 20, 2)</tt>
@param container A <tt>sequence<TYPE></tt> or generator which produces <tt>TYPE</tt>.
@param start The first item to return.
@param end The last item to return (-1 = all, only permitted for sequences).
@param stride The number of items to increment each time (1 = all).
@returns A <tt>sequence<TYPE></tt> containing the selected values from <tt>container</tt>
*/
static action slice(any container, integer start, integer end, integer stride) returns any
{
if start < 0 { throw com.apama.exceptions.Exception("Cannot start a slice at a negative number", "argumentException"); }
if stride < 1 { throw com.apama.exceptions.Exception("Slice stride must be at least 1", "argumentException"); }
string tn := container.getTypeName();
any slice := new any;
if tn.find("sequence<") = 0 {
slice := any.newInstance(tn);
action<> returns integer getsize := <action<> returns integer> container.getAction("size");
integer size := getsize();
action<sequence<any>> returns any append := slice.getAction("append").getGenericAction();
sequence<any> args := [new any];
integer i := start;
end := integer.min(end, size);
if end < 0 { end := size; }
while i < end {
args[0] := container.getEntry(i);
any _ := append(args);
i := i + stride;
}
} else if container.hasAction("generate") {
if end < 0 { throw com.apama.exceptions.Exception("Cannot end a slice of a generator at a negative number", "argumentException"); }
action<> returns any generate := <action<> returns any> container.getAction("generate");
any value := generate();
if slice.empty() {
slice := any.newInstance("sequence<"+value.getTypeName()+">");
}
action<sequence<any>> returns any append := slice.getAction("append").getGenericAction();
sequence<any> args := [new any];
integer i := 0;
while i < start { value := generate(); i := i + 1; }
while i < end {
args[0] := value;
any _ := append(args);
integer j := 0;
while j < stride { value := generate(); i := i + 1; j := j + 1; }
}
} else {
throw com.apama.exceptions.Exception("Can only slice sequence or generator", "typeException");
}
return slice;
}
/**
Create a generator from a function, which is passed the previous value and should return the next value.
The initial value will be a default-initialized <tt>TYPE</tt> and the result of first generation will be the result of invoking <tt>func</tt> on that default-initialized value. To specify the initial value, use generateFrom.
eg: <tt>Fn.generator((integer i)->i+1)</tt>
@param func An <tt>action<TYPE> returns TYPE</tt> action or lambda which takes the previous value and returns the next value.
@returns A generator for <tt>TYPE</tt>.
*/
static action generator(any func) returns Generator
{
return Generator.create(Util.returnTypeInstanceOf(func), func);
}
/**
Create a generator from a function, which is passed the previous value and should return the next value.
eg: <tt>Fn.generatorFrom(100, (integer i)->i+1)</tt>
@param start The value to pass to func to generate the first generation.
@param func An <tt>action<TYPE> returns TYPE</tt> action or lambda which takes the previous value and returns the next value.
@returns A generator for <tt>TYPE</tt>.
*/
static action generatorFrom(any start, any func) returns Generator
{
return Generator.create(start, func);
}
/**
Increments the given integer
*/
static action increment(integer i) returns integer { return i+1; }
/**
Returns a generator producing sequential integers with the first one being 0.
*/
static action count() returns Generator
{
return generatorFrom(-1, increment/* (integer i) -> i+1 */);
}
/**
Returns a generator producing random numbers between 0 and the value provided, of the type provided.
*/
static action random(any limit) returns Generator
{
return Generator.create(new any, RandomGenerator.create(limit).generate);
}
/**
Returns a range of integers from <tt>start</tt> (inclusive) to <tt>end</tt> (exclusive), incrementing <tt>stride</tt> each time.
*/
static action range(integer start, integer end, integer stride) returns sequence<integer>
{
// better would be slice(generatorFrom(start-1, (integer i)->i+stride), 0, (end-start)/stride, 1)
return <sequence<integer>> slice(generatorFrom(start-1, increment), 0, end-start, stride);
}
/** @private */
static action identity(any a) returns any { return a; }
/**
Repeats the given element forever.
@param item The item to return.
@returns A generator which returns item over and over again.
*/
static action repeat(any item) returns Generator
{
return generatorFrom(item, identity/* (any a)->a */);
}
/** Iterates through a sequence of items and continues looping forever.
@param seq The sequence of values to iterate over
@returns A generator which iterates over <tt>seq</tt>
*/
static action cycle(any seq) returns Generator
{
return generator(SequenceCycleGenerator.create(seq).generate);
}
/** Iterates through a sequence, or a generator and uses the result as a list of arguments with which to invoke a function.
These inner sequences will be treated as a list of arguments to the given function, or a single argument to that function.
Each generated item will be the result of calling func with the next set of arguments.
@param container A sequence or a generator.
@param func A function which takes each item in container and returns a result.
*/
static action argmap(any container, any func) returns Generator
{
action<sequence<any>> returns any source;
if container.hasAction("generate") {
source := container.getAction("generate").getGenericAction();
} else if container.getTypeName().find("sequence<") = 0 {
source := (<any>cycle(container).generate).getGenericAction();
} else {
throw com.apama.exceptions.Exception("Can only argmap over a sequence or generator", "typeException");
}
return generator(ArgMapGenerator.create(source, func).generate);
}
/**
Returns a sequence containing the given item the given number of times.
@param item The element to put in the sequence.
@param n The number of times to repeat the element.
@returns A <tt>sequence<ITEMTYPE></tt> with <tt>n</tt> <tt>item</tt>s in it.
*/
static action sequenceOf(any item, integer n) returns any
{
return slice(repeat(item), 0, n, 1);
}
/**
Returns a generator which accumulates over the underlying container, returning the result after accumulating each item.
Similar to reduce, but returns a generator for each item in turn, rather than just the final total.
The initial value of the accumulator is the default value of func's return type (<tt>TYPEB</tt>).
@param container The sequence, dictionary or generator to accumulate.
@param func An <tt>action<TYPEB,TYPEA> returns TYPEB</tt> action or lambda which accumulates each item in turn and returns the new total.
@returns A generator which returns each accumulated item in turn.
@see reduce
*/
static action accumulate(any container, any func) returns Generator
{
return accumulateFrom(Util.returnTypeInstanceOf(func), container, func);
}
/**
Returns a generator which accumulates over the underlying container, returning the result after accumulating each item.
Similar to reduce, but returns a generator for each item in turn, rather than just the final total.
@param start The initial value of the accumulator; must have the same type as func's return type (<tt>TYPEB</tt>).
@param container The sequence, dictionary or generator to accumulate.
@param func An <tt>action<TYPEB,TYPEA> returns TYPEB</tt> action or lambda which accumulates each item in turn and returns the new total.
@returns A generator which returns each accumulated item in turn.
@see reduceFrom
*/
static action accumulateFrom(any start, any container, any func) returns Generator
{
return Generator.create(new any, AccumulateGenerator.createFrom(start, container, func).generate);
}
/**
Action for adding up a sequence or generator of integer, float or decimal using accumulate or reduce.
eg: <tt>integer sum := Fn.reduce(numbers, Fn.sum);</tt>
*/
static action sum(any acc, any i) returns any
{
switch (i) {
case integer: {
if acc.empty() { acc := 0; }
return i+<integer> acc;
}
case float: {
if acc.empty() { acc := 0.; }
return i+<float> acc;
}
case decimal: {
if acc.empty() { acc := 0.d; }
return i+<decimal> acc;
}
}
}
/**
Returns an action for taking the mean of a sequence or generator of integer, float or decimal using accumulate or reduce.
eg: <tt>integer mean := Fn.reduce(numbers, Fn.mean());</tt>
*/
static action mean() returns action<any, any> returns any
{
return (new MeanFunctor).mean;
}
/**
Action for multiplying together the values in a sequence or generator of integer, float or decimal using accumulate or reduce.
eg: <tt>integer product := Fn.reduce(numbers, Fn.mul);</tt>
*/
static action mul(any acc, any i) returns any
{
switch (i) {
case integer: {
if acc.empty() { acc := 1; }
return i*<integer> acc;
}
case float: {
if acc.empty() { acc := 1.; }
return i*<float> acc;
}
case decimal: {
if acc.empty() { acc := 1.d; }
return i*<decimal> acc;
}
}
}
/**
Action which concatenates strings using accumulate or reduce.
*/
static action concat(string acc, string i) returns string
{
return acc+i;
}
/**
Returns true if the item has a field with the given value.
Use with Fn.partial to provide the field name and field value.
*/
static action fieldEqual(any fieldName, any fieldValue, any object) returns boolean
{
return object.getEntry(fieldName) = fieldValue;
}
/**
A predicate which returns true if the argument is even.
*/
static action even(integer i) returns boolean
{
return i%2=0;
}
/**
A predicate which returns true if the argument is odd.
*/
static action odd(integer i) returns boolean
{
return i%2=1;
}
/** A predicate which returns true if the argument is a whole number. */
static action whole(any i) returns boolean
{
switch (i) {
case integer: { return true; }
case float: { return i.fractionalPart() = 0.; }
case decimal: { return i.fractionalPart() = 0.d; }
}
}
/** A predicate which returns true if the argument is positive (not including 0). */
static action positive(any i) returns boolean
{
switch (i) {
case integer: { return i > 0; }
case float: { return i > 0.; }
case decimal: { return i > 0.d; }
}
}
/** A predicate which returns true if the argument is negative. */
static action negative(any i) returns boolean
{
switch (i) {
case integer: { return i < 0; }
case float: { return i < 0.; }
case decimal: { return i < 0.d; }
}
}
/** A predicate which returns true if the argument is less than the given threshold. */
static action lt(any thresh, any i) returns boolean
{
switch (i) {
case integer: { return i < <integer> thresh; }
case float: { return i < <float> thresh; }
case decimal: { return i < <decimal> thresh; }
}
}
/** A predicate which returns true if the argument is greater than the given threshold. */
static action gt(any thresh, any i) returns boolean
{
switch (i) {
case integer: { return i > <integer> thresh; }
case float: { return i > <float> thresh; }
case decimal: { return i > <decimal> thresh; }
}
}
/** A predicate which inverts the value of another predicate. */
static action _not(any pred) returns action<any> returns boolean
{
return NotPred.create(pred).execute;
}
/** Partially execute a function, providing some arguments, to be later executed with the remaining arguments.
Arguments must be provided left-to-right for the function call to be invoked.
eg: <tt>Partial p := Fn.partial(concatFn, "Hello"); <string>p.exec(" world");</tt>
Partial objects can be passed to any of the other actions on Fn where an action would be expected.
@param args The arguments to store for later execution. May be a single argument, or a sequence of several arguments.
@param func A function (including an earlier partial()) to execute once all arguments are provided.
*/
static action partial(any func, any args) returns Partial
{
return Partial.create(args, func);
}
/** TODO - run func on pair-wise elements of two iterables
static action zipfn(any containerA, any containerB, any func) returns Generator {} */
/** TODO - take any number of arguments and return them in a sequence
static action combine(sequence<any> args) returns any {} */
/** TODO - zipfn with combine as the fn
static action zip(any containerA, any containerB) returns Generator {} */
/** Consume a given number of items from a generator and discard them.
@param generator The generator to step.
@param n The number of times to step it.
@returns a reference to the original generator, stepped n times.
*/
static action consume(any generator, integer n) returns any
{
action<sequence<any>> returns any generate := generator.getAction("generate").getGenericAction();
sequence<any> args := new sequence<any>;
while n > 0 {
any _ := generate(args);
n := n - 1;
}
return generator;
}
/** @private */
static action incrementIfTrue(action<sequence<any>> returns any pred, sequence<any> args, integer count, any value) returns integer
{
args[0] := value;
if <boolean>pred(args) {
return count+1;
} else {
return count;
}
}
/** Counts how many times a predicate is true for the values of a sequence or dictionary.
eg: <tt>Fn.quantify(numbers, Fn.even)</tt>
@param container A sequence or dictionary.
@param pred An action<TYPE> returns boolean.
@returns The number of values in the container for which the predicate returns true.
*/
static action quantify(any container, any pred) returns integer
{