/
stdlib.ngs
6577 lines (5547 loc) · 197 KB
/
stdlib.ngs
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
STDLIB_EOL = "\n"
STDLIB_PATH_SEP = '/'
STDLIB_MAX_RAND_REAL = Real(RAND_MAX)
STDLIB_RAND_SAFETY_MAX = 100
{
GC.attrs({'doc': {'': 'Control NGS garbage collection'}})
GC['enable'].attrs({'doc': {'': 'Enable garbage collection'}})
GC['disable'].attrs({'doc': {'': 'Disable garbage collection'}})
GC['get_parallel'].attrs({'doc': {'': 'Check parallel garbage collection. Please do not use!', '%STATUS': 'internal'}})
}
doc Deprecated. Use ExitCode.
doc %STATUS - deprecated
F to_exit_code(x) {
warn("Using deprecated to_exit_code(). Use ExitCode() instead")
ExitCode(x)
}
doc Do nothing
doc %RET - null
F nop(*args, **kwargs) null
# === Trivial init() helper ===
doc Trivial initialization helper for init(o, ...)
doc Sets object fields from the supplied parameters
doc %EX - # sets t.a and t.b
doc %EX - F init(t:MyType, a, b) init(args())
F init(h:Hash) {
dst_kv = ll_hash_head(h)
dst = dst_kv.ll_hash_entry_val() # dst - value of first Hash entry
e = dst_kv.ll_hash_entry_next()
while e != null {
dst.(e.ll_hash_entry_key()) = e.ll_hash_entry_val()
e .= ll_hash_entry_next()
}
dst
}
# === Exceptions ===
{
doc Represents failed assertion, thrown by assert(). Should be used to catch programming errors.
doc %EXSYN - commands
doc %EX - F box_area(x:Int, y:Int) {
doc %EX - assert(x > 0)
doc %EX - assert(y > 0)
doc %EX - x * y
doc %EX - }
doc %EX - echo(box_area(5, 10))
doc %EX - # Output: 50
doc %EX - echo(box_area(-5, 10))
doc %EX - # ... Exception of type AssertFail ...
doc %EX - #
doc %EX - # Note that the following is better than using assert():
doc %EX - # not(x > 0) throws InvalidArgument('x must be greater than zero').set('x', x)
type AssertFail
AssertFail.inherit(Exception)
doc Represents an attempt to create an instance of an abstract type (not intended for instantiation).
type InstantiatingAbstractType
InstantiatingAbstractType.inherit(Exception)
}
doc IndexNotFound exception constructor
doc %RET - IndexNotFound object with the given message, container and key fields
F init(e:IndexNotFound, message:Str, container, key) init(args())
doc Throws AssertFail with givens message if condition is false
doc %RET - Unspecified, do not count on this value
doc %EX - my_array=[]
doc %EX - # ... Code that adds elements to my_array ...
doc %EX - assert(my_array.len() > 3, "my_array must have more than 3 elements") # AssertFail exception, with the given message
F assert(condition:Bool, msg:Str) not(condition) throws AssertFail(msg)
doc Throws AssertFail if condition is false
doc %RET - Unspecified, do not count on this value
doc %EX - my_array=[]
doc %EX - # ... Code that adds elements to my_array ...
doc %EX - assert(my_array.len() > 3) # AssertFail exception, with "Assertion failed" message
F assert(condition:Bool) assert(condition, "Assertion failed")
doc Throws AssertFail if condition, after conversion to Bool is false.
doc Same as super(Bool(condition), *args) .
doc condition - not Bool
doc %RET - Unspecified, do not count on this value
doc %EX - assert(my_array, "my_array must have elements at this point")
F assert(condition, *args) {
guard condition is not Bool
super(Bool(condition), *args)
}
doc Initializes InstantiatingAbstractType.
F init(e:InstantiatingAbstractType, t:Type) init(args())
# === Namespaces =================================
doc Get NormalType object field. Useful when calling method stored in an field.
doc %EX - myobj::method_in_field(arg) # calls method stored in myobj.method_in_field
doc %EX - (myobj.method_in_field)(arg) # calls method stored in myobj.method_in_field
doc %EX - myobj.method_in_field(arg) # calls global "method_in_field"
F '::'(nti:NormalTypeInstance, k) nti.(k)
doc Get Hash key. Useful when calling method stored in a Hash key.
doc Useful for working with namespaces, which are implemented as Hash instances.
doc %EX - elb = AWS::Elb(...).converge(...)
F '::'(h:Hash, k) h[k]
doc Set NormalType object field. It's implemented to complete the :: operator. There is no particular use case.
F '::='(nti:NormalTypeInstance, k, v) nti.(k) = v
doc Set Hash key. It's implemented to complete the :: operator. There is no particular use case.
F '::='(h:Hash, k, v) h[k] = v
# === Return =====================================
doc Implements calling of Return type instances
doc like the finish(i) call in the example below
doc %EX - F first(r:NumRange, predicate:Fun) {
doc %EX - finish = Return()
doc %EX - r.each(F(i) {
doc %EX - predicate(i) throws finish(i)
doc %EX - })
doc %EX - null
doc %EX - }
F call(r:Return, v=null) {
r.val = v
r
}
# === MultiMethod ================================
ns {
global each
# Preventing execution of F Arr(Eachable1) defined below.
# It causes infinite loop when tries to convert Eachable1 MultiMethod: it uses this each(), which uses Arr()
basic_arr = MultiMethod(Arr.constructors.Arr())
doc Call cb for each method of the MultiMethod
doc %EX - echo.each(F(method) echo("${method.params().name.join(", ")}"))
F each(mm:MultiMethod, cb:Fun) mm.basic_arr().each(cb)
}
F Str(mm:MultiMethod) "<MultiMethod with ${mm.Arr().len()} method(s)>"
# === Misc functional ============================
{
doc Parent type of all types that have each() method
type Eachable
doc Eachable which each() calls the callback with one argument
type Eachable1
Eachable1.inherit(Eachable)
doc Eachable which each() calls the callback with two arguments
type Eachable2
Eachable2.inherit(Eachable)
Int.inherit(Eachable1)
Arr.inherit(Eachable1)
Str.inherit(Eachable1)
MultiMethod.inherit(Eachable1)
# TODO: Consider Eachable2 subtype for Hash (as callback has 2 arguments)
Hash.inherit(Eachable2)
doc Absence of data
type NoData
Null.inherit(NoData)
doc A number
type Num
Int.inherit(Num)
Real.inherit(Num)
doc Make empty array
doc %RET - []
F Arr() { [] }
doc Make empty hash
doc %RET - {}
F Hash() { {} }
doc Make empty string
doc %RET - ''
F Str() { '' }
doc Get zero
doc %RET - 0
F Int() { 0 }
doc Get zero
doc %RET - 0.0
F Real() { 0.0 }
}
doc The identity function. Simply returns the given parameter.
doc %RET - The given argument
F identity(x) x
TEST identity(10) == 10
# TODO: Add more info about the newly created function - useful for debugging
# See https://docs.python.org/2/library/functools.html#partial-objects
doc Returns partially-applied function
doc f - The base function
doc Xunderscore_unsupportedXbind_args - The arguments to partial apply (bind the function to)
F partial(f:Fun, *bind_args)
F(*args) f(*bind_args, *args)
TEST p = partial((-), 10); p(7) == 3
doc Same as partial() but the bound arguments are last ones
F partial_tail(f:Fun, *bind_args)
F(*args) f(*args, *bind_args)
TEST p = partial_tail((-), 10); p(7) == -3
doc Sets the given field to the given value
doc %RET - The modified obj
doc %EX - s.len() != 1 throws InvalidArgument("ord() argument must be of length 1 exactly").set('given', s)
doc %EX - # Would else be written as
doc %EX - if s.len() != 1 {
doc %EX - e = InvalidArgument("ord() argument must be of length 1 exactly")
doc %EX - e.given = s
doc %EX - throw e
doc %EX - }
F set(obj, field:Str, val) {
obj.(field) = val
obj
}
doc Sets the given fields to the given values
doc %RET - The modified obj
doc %EX - my_cond throws InvalidArgument("Out of range").set(min=0, max=10, given=12)
F set(obj, **kwargs) {
kwargs.each(obj.set(X, Y))
obj
}
TEST type T; t=T().set(a=1, b=2); t.a == 1 and t.b == 2
doc Convert anything to a predicate.
doc anything - The value to compare to
doc %RET - A function that compares the only argument to the given value
doc %STATUS - deprecated
F Pred(anything:BasicTypeInstance) {
warn("Using deprecated Pred(BasicTypeInstance)")
F eq_pred(x) x == anything
}
doc Convert Hash to a predicate. The predicate asserts that
doc object fields named after h hash keys return true for predicates made of corresponding hash values.
doc Inspired by underscorejs' "matcher"
F Pred(h:Hash) {
preds = h.mapv(Pred)
F hash_pred(x) {
preds.all(F(k, pred) (k in x) and x.(k).pred())
}
}
TEST Pred({"a": Any})({"a": 1})
TEST Pred({"a": Any, "b": Any})({"a": 1}) == false
TEST Pred({"a": Any, "b": {false}})({"a": 1, "b": 2}) == false
doc Convert a function to predicate.
doc %RET - The given function, without any transformation
F Pred(f:Fun) f
doc Convert a type to a predicate.
doc t - A type
doc %RET - A function that checks whether the only argument is of type t
F Pred(t:Type) F is_pred(x) x is t
doc Map e to an Arr (array) of values using mapper.
doc e - Object of any type that has each(e, callback) implemented
doc %RET - Arr
doc %EX - [1,2,3].map(X*4) # [4,8,12]
F map(e:Eachable, mapper:Fun)
collector
e.each(collect + mapper)
doc EXPERIMENTAL! Do not use!
doc Map e to same type. Mnemonics: "map original" / "MAP to Original type".
doc e - object of any type that has each(e, callback) implemented
doc e - Eachable1. WARNING: instances of same type as e must have empty constructor and push() method.
doc %RET - Of same type as e
doc %STATUS - experimental
doc %EX - Set([1,2]).mapo(X*2) # Set([2,4])
F mapo(e:Eachable1, mapper:Fun) {
t = typeof(e)
ret = t()
e.each(F(elt) {
ret.push(mapper(elt))
})
ret
}
TEST Set([1,2]).mapo(X*2) == Set([2,4])
doc Transform mapper to handle only items matching predicate. Non-matching items will be returned as is.
doc %EX - ["abc", 1, "def", 2].map(only(Int, X*2)) # ["abc", 2, "def", 4]
F only(predicate, mapper:Fun) {
p = Pred(predicate)
F wrapped_in_only(elt) {
if p(elt) {
mapper(elt)
} else {
elt
}
}
}
TEST ["abc", 1, "def", 2].map(only(Int, X*2)) == ["abc", 2, "def", 4]
doc Filter e using predicate.
doc e - Eachable1. WARNING: instances of same type as e must have empty constructor and push() method.
doc predicate - Decision function to be called with each item as first argument.
doc predicate - When predicate(item) returns true, the item will appear in the resulting array.
doc %EX - (1...10).filter(F(num) num % 2 == 0) # Gives [2,4,6,8,10]
doc %EX - (1...10).filter(X<5) # Gives [1,2,3,4], predicate called as predicate(item, 5)
doc %RET - Of same type as e
F filter(e:Eachable1, predicate) {
pred = Pred(predicate)
t = typeof(e)
ret = t()
e.each() do F(elt) {
if pred(elt)
ret.push(elt)
}
ret
}
doc DEPRECATED! Do not use!
doc Use something.filter({field: predicate}) instead.
doc %STATUS - deprecated
F filter(something:Eachable1, field:Str, predicate) {
p = Pred(predicate)
something.filter({ p(A.(field)) })
}
doc Partition elements in something according to the predicate into two arrays.
doc First array contains all elements for which predicate(elt) is true and
doc the second array contains all elements for which predicate(elt) is false.
doc something - Eachable1
doc %RET - Array with two arrays in it
doc %EX - partition([1,10,2,20], X>=10) # [[10, 20], [1, 2]]
F partition(something:Eachable1, predicate) {
p = Pred(predicate)
ret = [[], []]
something.each(F(elt) ret[p(elt).not().Int()].push(elt))
ret
}
TEST partition([1,10,2,20], X>=10) == [[10, 20], [1, 2]]
{
type ElementNotFound
ElementNotFound.inherit(LookupFail)
}
doc Find first element in e that satisfies the predicate.
doc %RET - Either the element or the provided default if element was not found.
doc %EX - (10..20).first(F(x) x % 3 == 0) # 12 - first item divisible by 3
doc %EX - (10..20).first(F(x) x % 50 == 0, 1000) # 1000
F first(e:Eachable1, predicate, default) {
p = Pred(predicate)
finish = Return()
e.each(F(i) {
p(i) throws finish(i)
})
default
}
TEST [1,2,3].first(X>1, 10) == 2
TEST [1,2,3].first(X>5, 10) == 10
doc Find first element in e that satisfies the predicate. Throws ElementNotFound exception if no such element is found.
doc %RET - The element.
doc %EX - (10..20).first(F(x) x % 3 == 0) # 12 - first item divisible by 3
doc %EX - (10..20).first(F(x) x % 50 == 0) # ElementNotFound exception
F first(e:Eachable1, predicate) {
p = Pred(predicate)
finish = Return()
e.each(F(i) {
p(i) throws finish(i)
})
throw ElementNotFound("first() did not find the element").set('container', e).set('predicate', predicate)
}
TEST [1,2,3].first(X>1) == 2
TEST try [1,2,3].first(X>5) catch(e:ElementNotFound) true
doc Find first element in e that satisfies Bool(e) == true.
doc Exactly same as first(e, identity).
doc %EX - [false, 0, null, "xyz", 100].first() # "xyz"
doc %EX - [].first() # ElementNotFound exception
F first(e:Eachable1) first(e, identity)
doc Find the only element that satisfies the predicate.
doc Throws ElementNotFound exception if there are no elements that satisfy the predicate or if there is more than one element that satisfies the predicate.
doc %RET - The only element that satisfies the predicate.
F the_one(e:Eachable1, predicate) {
p = Pred(predicate)
ret = EmptyBox()
e.each() do F(elt) {
if p(elt) {
ret throws ElementNotFound("the_one() had more than one match").set('container', e).set('predicate', predicate)
ret = FullBox(elt)
}
}
not(ret) throws ElementNotFound("the_one() had no matches").set('container', e).set('predicate', predicate)
ret.get()
}
TEST [1,2,11,3,4].the_one(X>10) == 11
TEST try [1,2,11,12,4].the_one(X>10) catch(e:ElementNotFound) true
TEST try [1,2,3,4].the_one(X>10) catch(e:ElementNotFound) true
doc Find the only element that satisfies the predicate and execute given code with the value
doc body - The code to execute when exactly one element that satisfies the predicate was found. Executed with the found value. It's value will be returned as result of the_one().
doc found_more - The code to execute when more than one element satisfies the predicate. It's value will be returned as result of the_one(). Defaults to function returning null.
doc found_none - The code to execute when none of the elements satisfy the predicate. It's value will be returned as result of the_one(). Defaults to function returning null.
doc %RET - Result of running on of the following: body, found_more, found_none
doc %EX - F name(dn:MethodDocNode) {
doc %EX - dn.children.the_one(MethodNameDocNode).text[0]
doc %EX - }
F the_one(e:Eachable1, predicate, body:Fun, found_more:Fun=nop, found_none:Fun=nop) {
p = Pred(predicate)
ret = EmptyBox()
r = Return()
e.each(F(elt) {
if p(elt) {
if ret {
throw r(found_more())
}
ret = FullBox(elt)
}
})
if ret {
body(ret.get())
} else {
found_none()
}
}
TEST ok = false; [1,2,11,3,4].the_one(X>10, F(the_value) { if(the_value == 11) ok = true }); ok
TEST ok = false; [1,2,11,3,4].the_one(X>20, { does_not_matter }, found_none = { ok = true }); ok
TEST ok = false; [1,2,11,3,4].the_one(Int, { does_not_matter }, found_more = { ok = true }); ok
doc Extract the only element.
doc Throws ElementNotFound exception if there are no elements or if there is more than one element.
doc %RET - The only element.
doc %EX - ``aws ec2 describe-security-groups --group-ids $sg_id``.the_one() # {OwnerId=..., VpcId=..., GroupId=..., ...}
F the_one(e:Eachable1) e.the_one({true})
doc Filter nulls out.
doc DEPRECATED, USE something.without(null) INSTEAD.
doc something - Object of any type that has each(something, callback) implemented
doc %STATUS - deprecated
doc %RET - Arr (array) of original items without nulls
F filter(e:Eachable1) {
warn("Using deprecated filter(e)")
filter(e, X is not Null)
}
TEST [1,2,null,3].filter() == [1,2,3]
doc Filter something to an Arr (array) of values using predicate
doc predicate - Decision function to be called with each item as first argument.
doc predicate - When predicate(item) returns true, the item will not appear in the resulting array
doc something - object of any type that has each(something, callback) implemented
doc %EX - (1...10).reject(F(num) num % 2 == 0) # Gives [1,3,5,7,9]
doc %EX - (1...10).reject(X<5) # Gives [5,6,7,8,9,10], predicate called as predicate(item, 5)
doc %RET - Arr
F reject(something:Eachable, predicate) {
p = Pred(predicate)
something.filter(not + p)
}
doc EXPERIMENTAL! Do not use!
doc %STATUS - experimental
doc %EX - [1,2,3,1,2].take(X<3) # [1,2]
F take(something:Eachable1, predicate)
collector {
p = Pred(predicate)
r = Return()
something.each(F(elt) {
if p(elt)
collect(elt)
else
throw r()
})
}
TEST [1,2,3,1,2].take(X<3) == [1,2]
# Would look much better with an iterator of e.
doc EXPERIMENTAL! Do not use!
doc Filters out items that satisfy predicate at the begginning of e.
doc %STATUS - experimental
doc %EX - [1,2,3,1,2].drop(X<3) # [3,1,2]
F drop(e:Eachable1, predicate)
collector {
p = Pred(predicate)
found = false
e.each(F(elt) {
if found { collect(elt); return null; }
if not(p(elt)) {
collect(elt)
found = true
}
})
}
TEST [1,2,3,1,2].drop(X<3) == [3,1,2]
doc Replace all occurrences of src with dst
doc TODO: Return same type, not Arr
doc something - object of any type that has each(something, callback) implemented
doc %RET - Arr
doc %EX - ["ssh", "IP", "w"].replace("IP", "10.0.0.100") # ['ssh','10.0.0.100','w']
F replace(something:Eachable1, src, dst) map(something, only(X == src, {dst}))
TEST ["ssh", "IP", "w"].replace("IP", "10.0.0.100") == ['ssh','10.0.0.100','w']
doc Combine items to a single value using the supplied binary function
doc First f is applied to start and the first element of something
doc then on each step f is applied to previous result and next element
doc of something.
doc start - First argument of f, for the first call of f
doc something - object of any type that has each(something, callback) implemented
doc f - The combining function
doc %EX - F sum(something) something.reduce(0, (+))
F reduce(something:Eachable1, start, f:Fun) {
ret = start
something.each(F(elt) ret = f(ret, elt))
ret
}
TEST [1,2,3].reduce(0, (+)) == 6
{
type EmptyEachableFail
EmptyEachableFail.inherit(InvalidArgument)
}
doc Combine items to a single value using the supplied binary function
doc First f is applied to the first two elements of e
doc then on each step f is applied to previous result and next element
doc of e. Throws EmptyEachableFail if e has no elements. If e has only
doc one element, that element is returned.
doc e - object of any type that has each(e, callback) implemented
doc f - The combining function
doc %EX - F sum(e) e.reduce((+))
F reduce(e:Eachable1, f:Fun) {
ret = EmptyBox()
e.each(F(elt) {
if ret {
ret .= map(F(val) f(val, elt))
} else {
ret = FullBox(elt)
}
})
not(ret) throws EmptyEachableFail("reduce(e:Eachable1, f:Fun): e must have at least one element").set('e', e)
ret.get()
}
TEST [10].reduce((+)) == 10
TEST [1,2,3].reduce((+)) == 6
TEST try [].reduce((+)) catch(e:EmptyEachableFail) true
doc Deprecated.
doc Map when there is more than one element. If there is exactly one element, it's left as is
doc mapper - Will be called with zero based index and successive elements from arr
doc %STATUS - deprecated
doc %RET - Arr
F map_base_idx(base, n:Int, mapper:Fun) {
warn("Using deprecated map_base_idx()")
n == 1 returns [base]
n.map(mapper(base, X))
}
doc Call cb with val
doc %RET - val
doc %EX - long_computation_part1().tap(F(x) echo("DEBUG: $x")).long_computation_part2()
F tap(val, cb:Fun) {
cb(val)
val
}
TEST ok=false; (7.tap({ if A == 7 ok = true}) == 7) and ok
doc Filter operator.
doc Same as calling x.filter(predicate)
doc %EX - [1,2,3,4] ? F(x) x > 2 # [3,4]
F ?(x, predicate:Fun) x.filter(predicate)
doc Map operator.
doc Same as calling x.map(mapper)
doc %EX - [1,2,3,4] / F(x) x * 10
F /(x, mapper:Fun) x.map(mapper)
doc Each operator.
doc Same as calling x.each(cb)
doc %EX - [1,2,3,4] % echo
F %(x, cb:Fun) x.each(cb)
doc Call operator.
doc Same as calling f(x)
doc %EX - [1,2,3,4] \ echo
F \(x, f:Fun) f(x)
doc Return a+b unless one of the arguments is falsy. In that case return that argument (a if both are falsy). Useful for building strings with optional parts.
doc %EX - status_detail = ' (' +? maybe_empty_array.join(',') +? ')'
doc %EX - echo("Status: ${main_status}${status_detail}")
doc %RET - a+b or a or b
F +?(a, b) {
not(a) returns a
not(b) returns b
a + b
}
doc Checks whether element x is in Eachable1
doc x - Needle
doc e - Haystack
doc %EX - 1 in [1,2,3].Iter() # true
doc %EX - 10 in [1,2,3].Iter() # false
doc %RET - Bool
F in(x, e:Eachable1) e.any(X == x)
TEST ( 1 in [1,2,3].Iter()) == true
TEST (10 in [1,2,3].Iter()) == false
doc Push all elements of e into dst.
doc %RET - dst
F push_all(dst, e:Eachable1) {
e.each(push(dst, X))
dst
}
TEST a=[1,2]; a.push_all([3,4]); a==[1,2,3,4]
# === Eachable1 ==================================
# Should be low priority (ordered before others) method
F +(a:Eachable1, b:Eachable1) {
guard typeof(a) === typeof(b)
t = typeof(a)
guard t != Int
guard t != Arr
guard t != Str
t().push_all(a).push_all(b)
}
TEST Lines(["ab", "cd"]) + Lines(["ef"]) == Lines(["ab", "cd", "ef"])
doc EXPERIMENTAL! Do not use!
doc Makes sure returned value is of type t. If x is already of type t, returns x.
doc Otherwise, returns object of type t with single item x.
doc t - a subtype of Eachable1
doc %RET - Object of type t
doc %STATUS - experimental
F ensure(x, t:Type) {
guard t.is_subtype(Eachable1)
typeof(x) === t returns x
t().push(x)
}
# === ArrLike ====================================
# TODO [doc]: examples in methods
{
doc Parent type for user-defined types with array-like behaviour. Use in cases when you would like to inherit from built-in Arr. Inheriting from built-ins is not possible for now.
doc items - default field for the underlying array
doc %EX - type T(ArrLike)
doc %EX - F Str(t:T) "<My array has ${len(t)} items totalling ${sum(t)}>" # Override one of the Arr methods
doc %EX - a = T()
doc %EX - a.push(10)
doc %EX - a.push(20)
doc %EX - echo(a) # <My array has 2 items totalling 30>
doc %EX -
doc %EX - # If you need init() you should have something like the following to allow ArrLike initialization:
doc %EX - init(t:T) {
doc %EX - super(t)
doc %EX - ...
doc %EX - }
type ArrLike
ArrLike.inherit(Eachable1)
}
F init(al:ArrLike) {
if al.attrs() is not Hash {
al.attrs({})
}
al.attrs().ArrLike = []
}
doc ArrLike constructor.
doc field - DEPRECATED name of the field that holds the underlying array.
doc Throws NotImplemented if field is specified
F init(al:ArrLike, field:Str=null) {
field throws NotImplemented("ArrLike(Str) is deprecated")
super(al)
}
F init(al:ArrLike, arr:Arr) {
super(al)
al.attrs().ArrLike = arr
}
doc Get length of the underlying array.
F len(al:ArrLike) al.attrs().ArrLike.len()
doc Set element in the underlying array.
F '[]'(al:ArrLike, idx:Int) al.attrs().ArrLike[idx]
doc Get element from the underlying array.
F '[]='(al:ArrLike, idx:Int, x) al.attrs().ArrLike[idx] = x
doc Get element at the given index or return dflt if the index is out of range (element at the given index does not exist). See get(Arr).
F get(al:ArrLike, idx:Int, dflt) al.attrs().ArrLike.get(idx, dflt)
doc Call cb for each element in the underlying array.
F each(al:ArrLike, cb:Fun) al.attrs().ArrLike.each(cb)
doc Check whether al has any elements.
F Bool(al:ArrLike) al.attrs().ArrLike.Bool()
# NOTE: Never run because of Arr(Eachable1)
doc Get the underlying array
F Arr(al:ArrLike) al.attrs().ArrLike
doc Push an element to the underlying array.
F push(al:ArrLike, val) {
al.attrs().ArrLike.push(val)
al
}
doc Join items to a single string using given seperator s
doc %RET - Str
F join(al:ArrLike, s:Str) al.attrs().ArrLike.join(s)
doc Return array made of given field of each element of given array.
doc Will throw KeyNotFound if any of the elements does not have the desired field.
doc Use get() to handle missing field differently.
F .(al:ArrLike, s:Str) al.attrs().ArrLike.(s)
doc Defines collector { ... collect(...) ... } behaviour for ArrLike.
doc Very similar to collector for Arr. See collector(Arr,Fun).
F collector(al:ArrLike, body:Fun) {
body(F(elt) al.push(elt))
al
}
# === HashLike ===================================
# TODO [doc]: examples in methods
{
doc Base type for user-defined hash-like types. This is a workaround: it's not possible currently no inherit from the built-in Hash type.
type HashLike
HashLike.inherit(Eachable2)
}
doc Check whether k is in the HashLike
doc %RET - Bool
F in(k, hl:HashLike) k in hl.attrs().HashLike
doc Get number of key-value pairs in a HashLike
doc %RET - Int
F len(hl:HashLike) hl.attrs().HashLike.len()
doc Get value by key. Throws KeyNotFound.
doc %AUTO - your_hashlike[k]
F '[]' (hl:HashLike, k) hl.attrs().HashLike[k]
doc Set value.
doc %AUTO - your_hashlike[k] = v
F '[]='(hl:HashLike, k, v) hl.attrs().HashLike[k] = v
doc Get value by key. Throws KeyNotFound.
doc %AUTO - your_hashlike.literal_key
doc %RET - Any
F .(hl:HashLike, k) hl.attrs().HashLike[k]
doc Set value.
doc %AUTO - your_hashlike.literal_key = v
doc %RET - v
F .=(hl:HashLike, k, v) hl.attrs().HashLike[k] = v
doc Get value by key or dflt if it does not exist
doc %RET - Any
F get(hl:HashLike, k, dflt) hl.attrs().HashLike.get(k, dflt)
doc Get value by key or null if it does not exist
doc %RET - Any
F get(hl:HashLike, k) hl.get(k, null)
doc Iterate over keys and values.
doc %EX - my_hashlike.each(F(k, v) echo("$k=$v"))
doc %RET - hl
F each(hl:HashLike, cb:Fun) {
hl.attrs().HashLike.each(cb)
hl
}
doc Get keys
doc %RET - Arr
F keys(hl:HashLike) hl.attrs().HashLike.keys()
doc Get values
doc %RET - Arr
F values(hl:HashLike) hl.attrs().HashLike.values()
doc Check whether hl has any elements.
doc %RET - Bool
F Bool(hl:HashLike) hl.attrs().HashLike.Bool()
F map_idx_key_val(hl:HashLike, mapper:Fun) hl.attrs().HashLike.map_idx_key_val(mapper)
doc Filter hash. Build new HashLike with kev-value pairs selected by predicate.
doc predicate - Test function to be called with one key and one value at a time.
doc %EX - my_hashlike.filter(F(k, v) k == 'a')
doc %RET - HashLike
F filter(hl:HashLike, predicate:Fun) {
ret = HashLike()
ret.attrs().HashLike = hl.attrs().HashLike.filter(predicate)
ret
}
doc Create a HashLike.
doc h - If provided, used as initial value.
doc %EX - HashLike(%{a aha b bee}) # <HashLike a=aha b=bee>
F init(hl:HashLike, h:Hash=null) {
if hl.attrs() is not Hash {
hl.attrs({})
}
hl.attrs().HashLike = h or {}
}
doc Get the underlying Hash with all the keys/values of the HashLike.
doc Note: the returned value is not a copy.
doc %RET - Hash
F Hash(hl:HashLike) hl.attrs().HashLike
# === Hook =======================================
{
doc Hook is a simple pub-sub
type Hook
Hook.inherit(HashLike)
}
doc Hook constructor.
doc %RET - Hook
F init(hook:Hook) {
super(hook)
hook.attrs().idx = 0
}
doc Add unnamed handler.
doc The hook is automatically named "pushed-N" where N is sequential integer.
doc %RET - New hook name
F push(hook:Hook, handler:UserDefinedMethod) {
name = "pushed-${hook.attrs().idx}"
hook.attrs().idx += 1
hook[name] = handler
name
}
# TODO: consider optional? try/catch isolation
doc Runs all handlers passing all args.
doc args - Arguments to pass to handlers
doc %RET - Arr. Results from all the handlers
F call(hook:Hook, *args) hook.attrs().HashLike.mapv(X(*args))
# === Real =======================================
# TODO: something more efficient
doc Convert a string to real (floating) number, inefficiently
doc %RET - Real
doc %EX - Real("1.1") # 1.1
F Real(s:Str) {
parts = s.split('.')
parts.len() == 1 returns Real(Int(parts[0]))
parts.len() != 2 throws InvalidArgument("Invalid argument ${s}")
l = parts[1].len()
frac = Real(Int(parts[1]))
for(i;l) frac = frac / 10.0
Real(Int(parts[0])) + frac
}
TEST Real('1.1') == 1.1
# === Fun helpers ================================
doc Do not use!
F StrParams(f:Fun) {
guard f is UserDefinedMethod or f is NativeMethod
f.params().map(F(p) {
d = if 'dflt' in p then '=...' else ''
"${p.get('splat', '')}${p.name}:${p.type.name}${d}"
}).join(', ') \ "($X)"
}
# === NativeMethod ===============================
doc String representation of native method.
doc %RET - "<NativeMethod NAME(PARAMS)>"
doc %EX - (%).Arr()[0].Str().echo() # Outputs: <NativeMethod %(a:Int, b:Int)>
F Str(nm:NativeMethod) "<${nm.typeof().name} ${nm.attrs().name}${StrParams(nm)}>"
# === NormalTypeConstructor ===============================
doc String representation of normal type constructor. NormalTypeConstructor
doc %RET - "<NormalTypeConstructor>"
doc %EX - Box.constructors.Arr()[0].Str().echo() # Outputs: <NormalTypeConstructor>
F Str(ntc:NormalTypeConstructor) "<NormalTypeConstructor>"
# === UserDefinedMethod ====================================
# TODO: show arguments:
# "<UserDefinedMethod ${c.attrs().name tor "<anonymous>"}(HERE) at ${location}>"
doc String representation of a closure
doc %RET - Str
doc %EX - Real.constructors[-1].Str().echo() # Outputs: <UserDefinedMethod Real at /usr/share/ngs/stdlib.ngs:350>
F Str(c:UserDefinedMethod) {
info = c.ip().resolve_instruction_pointer()
location = "${info.file}:${info.first_line}" tor "<unknown location>"
"<UserDefinedMethod ${c.attrs().name tor "<anonymous>"}${StrParams(c)} at ${location}>"
}
# === Type =======================================
doc Create a new type. Do not use directly.
doc %AUTO - type MyType2(MyType1)
F Type(t:Str, doc, ns, parent:Type) Type(t, doc, ns, [parent])
doc Create a new type. Do not use directly.
doc %AUTO - type MyType2([MyParent1, MyParent2, ...])
F Type(t:Str, doc, ns, parents:Arr) {
ret = Type(t, doc, ns)
parents % ret.inherit(X)
ret
}
TEST type T1; type T2(T1); T2() is T1
doc EXPERIMENTAL! Do not use! Especially don't count on returned value beyond obvios Bool(x) behaviour. Match anything.
doc %STATUS - deprecated
F ~(something, pred) {
warn("Using deprecated ~(something:Any, pred:Any)")
if Pred(pred)(something) {
MatchSuccess([something])
} else {
MatchFailure()
}
}
doc String representation of a type
doc %RET - "<Type NAME>"
doc %EX - Real.Str().echo() # Outputs: <Type Real>
F Str(t:Type) "<Type ${t.name}>"
doc Decode (parse) strings such as command line arguments or environment variables to result given type
doc TODO: Consider renaming to UnArgv or decode_arg
doc %STATUS - experimental
F decode(s:Str, t:Type) {
t == Any returns s # For ArgvMatcher
F _fail(cause:Exception=null) {
args = ["Failed to decode value. Could not convert given value to type ${t.name}", cause].reject(Null)
throw DecodeFail(*args).set('value', s).set('target_type', t)
}
if t in [Int, Real, Str] {
return try {
t(s)
} catch(e:InvalidArgument) {
_fail(e)
}
}
if t == Bool {
s ~ /^(1)|(y(es?)?)|true|on$/i returns true
s ~ /^(0)|(no?)|false|off$/i returns false
_fail()
}
guard false
}
TEST decode("no", Bool) == false
TEST decode("0", Bool) == false
TEST decode("yes", Bool) == true
TEST decode("1", Bool) == true
TEST decode("1", Int) == 1
TEST decode("1", Real) == 1.0
doc %STATUS - experimental
doc Check whether t is a subtype of maybe_supertype.
doc Note that if t and maybe_supertype are same type, this method also returns true.