-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
stdlib.mon
1046 lines (744 loc) · 18.9 KB
/
stdlib.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
//
// This file contains functions available by default, implemented in 100%
// pure monkey.
//
// i.e. This is part of our standard-library.
//
// If you wish to make changes to the standard-library functions in this
// file you'll need to rebuild the interpreter after making your changes.
//
// This file it is embedded in the generated-binary as part of the build
// process.
//
// go build .
//
//
// Mathematical constants
//
const PI = 3.141592653589793;
const E = 2.718281828459045;
//
// File-objects for STDIN, STDOUT, and STDERR.
//
// Rather than opening these by name/path we have magic-strings which
// are recognized by our "open" primitive.
//
const STDIN = open( "!STDIN!" );
const STDOUT = open( "!STDOUT!" );
const STDERR = open( "!STDERR!" );
//
// Functions with an "object." prefix are available to all types.
//
// With this definition in-place you can invoke the object-methods:
//
// "".type();
// 3.type();
// [].type();
// etc
//
// instead of having to run type( blah );
//
function object.type() {
return(type(self));
}
//
// Functions with an "object." prefix are available to all types.
//
// With this definition in-place you can invoke the object-methods:
//
// "".string();
// 3.string();
// [].string();
// etc
//
// instead of having to run string( blah );
//
function object.string() {
return(string(self));
}
//
// The `assert` method allows the code in our standard-library to be
// tested every time it is loaded.
//
function assert(val, msg = "Result was not 'true'!" ) {
if ( type(val) == "string") {
result = eval( val );
if ( !result ) {
puts( "assert(\"" , val, "\") failed - ", msg, "\n" );
exit(1);
}
}
else {
if ( ! val ) {
puts( msg, "\n" );
exit(1);
}
}
}
assert( "true" );
assert( true );
assert( "! false;" );
assert( !false );
assert( "type( STDIN ) == \"file\"" );
assert( "type( STDOUT ) == \"file\"" );
assert( "type( STDERR ) == \"file\"" );
//
// First element of an array
//
function first( array ) {
if ( len(array) >= 1 ) {
return( array[0] );
}
// return nil is implicit here.
}
assert( "first( [0,1] ) == 0" );
assert( "first([\"steve\",1]) == \"steve\"" );
assert( "!first([])" );
//
// The rest of an array - i.e. all elements EXCEPT the first
//
function rest( array ) {
let result = [];
if ( len(array) > 1 ) {
let i = 1;
for( i < len(array) ) {
result = push(result, array[i]);
i++;
}
}
return result;
}
assert( "type(rest([])) == \"array\"" );
assert( "len(rest( [0,2] ) ) == 1" );
assert( "len(rest( [0,1,2] ) ) == 2" );
assert( "len(rest( [0,1,2,3,4,5] ) ) == 5" );
assert( "string(rest([\"steve\",1])) == \"[1]\"" );
//
// Last element of an array
//
function last( array ) {
if ( len( array ) > 0 ) {
return(array[len(array)-1]);
}
// `return null` is implicit here.
}
assert( "last([0,2]) == 2" );
assert( "!last([])" );
//
// Is the given array empty?
//
function array.empty?() {
if ( len(self) == 0 ) {
return true;
}
return false;
}
assert( "[].empty?()" );
assert( "![1,2].empty?()" );
assert( "![\"steve\",3].empty?()" );
//
// Call the given function on each entry, and return an array of the
// items for which the predicate returned true.
//
function array.filter( predicate ) {
let i = 0;
let l = len(self);
let result = [];
for( i < l ) {
let entry = self[i];
if (predicate(entry)) {
let result = push( result, entry );
}
i++;
}
return result;
}
// Filter an array and keep only values which are "2".
assert( "let a = [ 1, 2, 3 , -1, \"steve\", 44 ];
let a = a.filter( fn(n) { return n == 2 ; } );
if ( a.string() == \"[2]\" ) {
return true;
} else {
puts( a );
return false;
}" );
//
// Return the offset, if any, of the specified item in the array.
//
function array.find(item) {
foreach index, value in self {
if ( value == item ) {
return index;
}
}
// not found.
return -1;
}
assert( "[1,2,3].find(7) == -1" );
assert( "[1,2,3].find(1) == 0" );
assert( "[1,2,3].find(3) == 2" );
assert( "[1,2,3,3].find(3) == 2" );
//
// Does the given value exist inside the array?
//
function array.includes?( obj ) {
return( self.find( obj ) != -1 );
}
assert( "[1,2,3].includes?(2)" );
assert( "! [1,2,3].includes?(23)" );
//
// Find minimum value in array
//
function array.min() {
let i = 0;
let l = len(self);
if ( l < 1 ) {
return 0;
}
// Assume first value is minimum
let min = self[0];
// type checking.
if ( type(min) != "integer" && type(min) != "float" ) {
puts( "array.min only works on numbers - not " , type(min), "\n");
exit(1);
}
// If we find a smaller one, set it.
for( i < l ) {
// type checking.
if ( type(self[i]) != "integer" && type(self[i]) != "float" ) {
puts( "array.min only works on numbers - not " , type(self[i]), "\n");
exit(1);
}
if ( self[i] < min ) {
min = self[i];
}
i++;
}
return min;
}
assert( "( [1,2,3].min() == 1 )" );
assert( "( 1..10.min() == 1 )" );
assert( "( [-1,-2,-3].min() == -3 )" );
assert( "( [].min() == 0 )", "minimum of an empty array is zero" );
//
// Find maximum value in array
//
function array.max() {
let i = 0;
let l = len(self);
if ( l < 1 ) {
return 0;
}
// Assume first value is maximum
let max = self[0];
// ensure we're dealing with types
if ( type(max) != "integer" && type(max) != "float" ) {
puts( "array.max only works on numbers - not " , type(max), "\n");
exit(1);
}
// If we find a greater one, set it.
for( i < l ) {
// type checking.
if ( type(self[i]) != "integer" && type(self[i]) != "float" ) {
puts( "array.max only works on numbers - not " , type(self[i]), "\n");
exit(1);
}
if ( self[i] > max ) {
max = self[i];
}
i++;
}
return max;
}
assert( "( 1..15.max() == 15 )" );
assert( "( [1,2,3].max() == 3 )" );
assert( "( [-1,-2,-3].max() == -1 )" );
assert( "( [].max() == 0 )", "maximum of an empty array is zero" );
//
// Join the elements of an array by the given string.
//
function array.join( char ) {
let r = "";
let i = 0;
let l = len(self);
// For each entry.
for( i < l ) {
// If the result is non-empty add the separator.
if ( len(r) > 0 ) {
r+= char;
}
// add on the next element.
r += string(self[i])
i++;
}
return r;
}
assert( "[1,2,3].join( \".\" ) == \"1.2.3\"" );
assert( "[1,2,3].join( \"\" ) == \"123\"" );
//
// Reverse an array.
//
function array.reverse() {
let r = [];
let l = len(self);
for( l > 0 ) {
let r = push( r, self[l-1] );
l--;
}
return r;
}
assert( "string([1,2,3].reverse()) == \"[3, 2, 1]\"" );
//
// sorted? returns true if the specified array is sorted.
//
function array.sorted?() {
// Ensure each array-member has the same type.
let tmp = {};
let i = 0;
// Record the types.
for( i < len(self) ) {
tmp = set(tmp, self[i].type(), true );
i++;
}
// There can be only one!
if ( len( keys( tmp ) ) > 1 ) {
puts( "Attempting to check an array with mixed-type values!\n" );
puts( string(self), "\n" );
exit(1);
}
let i = 1;
let l = len(self);
// Array of zero/one element is always sorted.
if ( l < 2 ) {
return true;
}
// If a later item is smaller than the
// earlier item the array is not sorted.
for( i < l ) {
if ( self[i] < self[i-1]) {
return false;
}
i++;
}
return true;
}
assert( "[-1,0,1].sorted?()" );
assert( "[1].sorted?()" );
assert( "[].sorted?()" );
//
// Swap the value of two array indexes.
//
// This is used by our sorting function. Currently it isn't possible
// to mutate an array-member in-place. So we create a new array
// correctly swapping the values at the given index.
//
// This would be easier if we had "elseif" support, or even a case
// statement. (Due to the nested if usage here.)
//
function array.swap( a, b ) {
let aVal = self[b];
let bVal = self[a];
let r = [];
let i = 0;
let l = len(self);
for( i < l ) {
if ( i == a ) {
let r = push(r, aVal);
} else {
if ( i == b ) {
let r = push(r,bVal );
} else {
let r = push( r, self[i] );
}
}
i++;
}
return r;
}
assert( "let a = [10,20]; a = a.swap(0,1); if ( a[0] == 20 ) { true; } else { false ; }" );
assert( "let a = [10,20]; a = a.swap(0,1); if ( a[1] == 10 ) { true; } else { false ; }" );
//
// Sort the given array.
//
// This is grossly inefficient, obviously.
//
function array.sort() {
// Ensure each array-member has the same type.
let tmp = {};
let i = 0;
// Record the types.
for( i < len(self) ) {
tmp = set(tmp, self[i].type(), true );
i++;
}
// There can be only one!
if ( len( keys( tmp ) ) > 1 ) {
puts( "Attempting to sort an array with mixed-type values!\n" );
puts( string(self), "\n" );
exit(1);
}
// While the given array isn't sorted.
for( ! self.sorted?() ) {
// make a pass over the array.
let i = 1;
let l = len(self);
for( i < l ) {
// if this element is wrong swap it.
if ( self[i] < self[i-1] ) {
self = self.swap( i-1, i);
}
i++;
}
}
// Should be done now.
return self;
}
assert( "let a = [ 3, 2, 1 ]; a = a.sort(); a.sorted?()" );
assert( "let a = [ 3, 2, 1 ]; a = a.sort(); a[0] == 1" );
assert( "let a = [ 3, 2, 1 ]; a = a.sort(); a[1] == 2" );
assert( "let a = [ 3, 2, 1 ]; a = a.sort(); a[2] == 3" );
//
// Return an array containing the result of applying the specified
// function to each element in the array.
//
// This is out of alphabetical order because our assert-based testing
// invokes sort, just to ensure consistent results.
//
function array.map( fnc ) {
let result = [];
foreach item in self {
let result = push( result, fnc(item) );
}
return result;
}
assert( "let a = [3,9,-4];
a = a.map(fn(n) { return n * n; });
a = a.sort();
if( a.string() == \"[9, 16, 81]\" ) {
true;
} else {
false;
}" );
assert( "let a = [2,-1,-12];
a = a.map(fn(n) { return n +2; });
a = a.sort();
if( a.string() == \"[-10, 1, 4]\" ) {
true;
} else {
false;
}" );
//
// array.uniq returns the unique members of an array.
//
function array.uniq() {
tmp = {};
foreach item in self {
tmp = set( tmp, item, true );
}
// return the sorted keys
return( tmp.keys().sort() );
}
assert( "string([1,1,1,1,2].uniq()) == \"[1, 2]\"" );
//
// Convert a float to an integer.
//
// Like Go we discard the value after the period, so 4.9 will become 4.
//
function float.to_i() {
return( int( self ) );
}
assert( "type( 3.1.to_i() ) == \"integer\"" );
assert( "let a = 3.1; if ( a.to_i() == 3 ) { return true; } else { return false ; } " );
//
// Is the given hash empty?
//
function hash.empty?() {
if ( len(self.keys()) == 0 ) {
return true;
}
return false;
}
assert( "{}.empty?()" );
assert( "! {\"name\":\"steve\"}.empty?()" );
//
// Convert an integer to a float.
//
function integer.to_f() {
return( self + 0.0);
}
assert( "type( 3.to_f() ) == \"float\"" );
assert( "3.to_f() == 3.0" );
//
// Count occurences of the given character in the string.
//
function string.count(char) {
let c = 0;
foreach chr in self {
if ( chr == char ) {
c += 1;
}
}
return c;
}
assert( "\"steve\".count(\"e\") == 2" );
assert( "\"steve\".count(\"E\") == 0" );
assert( "\"犬狐\".count(\"狐\") == 1" );
assert( "\"犬犬犬犬犬犬狐\".count(\"犬\") == 6" );
//
// Remove leading whitespace from the string.
//
function string.ltrim() {
let reg = "^(\\s+)(.*)$";
let out = match(reg, self);
if ( out ) {
return( out[1]) ;
} else {
return self;
}
}
assert( ( " 狐犬 ".ltrim() == "狐犬 "), "string.ltrim failed" );
assert( ( " steve ".ltrim() == "steve "), "string.ltrim failed" );
//
// Repeat a string N times.
//
function string.repeat(count) {
let r= "";
if ( count < 1 ) {
return self;
}
for( count > 0 ) {
r += self;
count--;
}
return r;
}
assert( ( "狐犬".repeat(3) == "狐犬狐犬狐犬"), "string.repeat failed" );
assert( ( "*".repeat(1) == "*"), "string.repeat failed" );
assert( ( "*".repeat(0) == "*"), "string.repeat failed" );
assert( ( "*".repeat(-1) == "*"), "string.repeat failed" );
//
// Reverse a string,
//
function string.reverse() {
let r= "";
let l = len(self);
for( l > 0 ) {
r += self[l-1];
l--;
}
return r;
}
assert( ( "狐犬".reverse() == "犬狐"), "string.reverse failed" );
assert( ( "322".reverse() == "223"), "string.reverse failed" );
//
// Remove trailing whitespace from the string.
//
function string.rtrim() {
let reg = "^(.*?)(\\s*)$";
let out = match(reg, self);
if ( out ) {
return( out[0]) ;
} else {
return self;
}
}
assert( ( " 狐犬 ".rtrim() == " 狐犬"), "string.rtrim failed" );
// string.substr returns the given substring
// from our input. The length of the string
// to return is optional, and will default to
// the length available.
//
// Note: Moved this ahead of where it is used in string.replace.
//
function string.substr(start,length = -1) {
// if there is no length then default to the rest of the string.
if ( length == -1 ) {
length = len(self) - start ;
}
// start must be positive
if ( start < 0 ) {
start = 0;
}
// if the length of the string is too big then we'll cap it too.
if ( start + length > self.len() ) {
length = len(self) - start ;
}
// catch bounding-errors.
if ( start >= len(self) ) {
return "";
}
let res = "";
let copied = 0;
for( (start < len(self)) && ( copied < length ) ) {
res += self[start];
start++;
copied++;
}
return( res );
}
assert( "Hello world".substr( 1,4 ) == "ello" , "string.substr() failed");
assert( "Hello world".substr( 6 ) == "world" , "string.substr() failed");
assert( "狐犬".substr( 0 ) == "狐犬" , "string.substr() failed");
assert( "犬狐".substr( 1 ) == "狐" , "string.substr() failed");
assert( "狐犬".substr( 2 ) == "" , "string.substr() failed");
assert( "狐犬".substr( 0,2 ) == "狐犬" , "string.substr() failed");
assert( "狐犬".substr( 1,2 ) == "犬" , "string.substr() failed");
assert( "狐犬".substr( 1,100 ) == "犬" , "string.substr() failed");
assert( "狐犬".substr( -1,100 ) == "狐犬" , "string.substr() failed");
//
// string.find returns the offset of the given substring
// or -1 if it isn't found.
//
function string.find( needle ) {
// get details about ourself
let i = 0;
let l = len(self);
// the length of our search string.
let L = len(needle);
// get a substring at each possible position
for( i < l ) {
possible = self.substr( i, L );
// does this match?
if ( possible == needle ) {
return i;
}
i++;
}
return -1;
}
assert( "\"steve\".find(\"e\" ) == 2" );
assert( "\"steve\".find(\"v\" ) == 3" );
assert( "\"steve\".find(\"PIE\" ) == -1" );
assert( "\"狐犬\".find(\"狐犬\" ) == 0" );
assert( "\"st狐eve犬es\".find(\"犬\" ) == 6" );
//
// string.interpolate replaces ${blah} with the value of "blah" from
// the specified hash.
//
function string.interpolate( hsh ) {
let reg = "(?s)^(.*?)\\$\\{([^\\}]+)\\}(.*)";
let out = match(reg, self);
for( out ) {
let pre = out[0];
let tok = out[1];
let pst = out[2];
let self = pre + string(hsh[tok]) + pst;
let out = match(reg, self);
}
return( self );
}
//
// string.split returns an array splitting on any characters included
// in the separator string.
//
// By default the split is on whitespace: " ", "TAB", & "RETURN".
//
function string.split(sep = " \r\t\n" ) {
let i = 0;
let l = len(self);
let r = [];
let tmp = "";
for( i < l ) {
// get the character.
let c = self[i];
// is the character one of our split-characters?
if ( sep.find( c ) != -1 ) {
// OK push any previously-accumulated token into our array.
if ( len(tmp) > 0 ) {
r = push( r, tmp );
}
tmp = "";
} else {
// store the character into our accumulator.
tmp += c;
}
i++;
}
// Do we have a dangling-string? If so append it.
if ( len(tmp) > 0 ) {
r = push(r,tmp);
}
return r;
}
assert( "len(\"1 2 3\".split()) == 3" );
assert( "type(\"1 2 3\".split(\"2\")) == \"array\"" );
//
// string.replace removes a value from a string, replacing it
// with a new value.
//
function string.replace( old, new ) {
let s = self;
let index = s.find( old );
for( index >= 0 ) {
// get the prefix
let pre = s.substr(0, index);
// get the suffix
let suf = s.substr( index + len(old) );
s = pre + new + suf;
index = s.find( old );
}
return s;
}
assert( "steve".replace( "e", "E" ) == "stEvE", "string.replace() failed" );
assert( "steve".replace( "A", "EE" ) == "steve", "string.replace() failed" );
//
// Trim leading & trailing whitespace from the given string.
//
function string.trim() {
let l = self.ltrim();
return( l.rtrim() );
}
assert( " ".trim() == "", "string.trim failed" );
assert( " 1 ".trim() == "1", "string.trim failed" );
//
// Convert the given string to lower-case.
//
function string.tolower() {
let r = "";
foreach char in self {
if ( char >= "A" && char <= "Z" ) {
char = char.ord();
char += 32;
char = char.chr();
}
r += char;
}
return r;
}
assert( "Steve".tolower() == "steve", "string.tolower() failed" );
assert( "狐犬".tolower() == "狐犬", "string.tolower() failed" );
//
// Convert a string to a number
//