This repository has been archived by the owner on Jul 22, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlunar.go
1588 lines (1490 loc) · 38.9 KB
/
lunar.go
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
// Lunar Logo: clean, minimal scripting language based on Logo and Lua.
package main
import (
"fmt"
"strings"
"strconv"
"regexp"
"os"
"bufio"
"sort"
"math"
"math/rand"
"time"
)
var Ins = os.Stdin
var Outs = os.Stdout
var Errs = os.Stderr
var intre = regexp.MustCompile(`^-?[[:digit:]]+$`)
var splitre = regexp.MustCompile(`[[:space:]]+`)
var spacere = regexp.MustCompile(`^[[:space:]]+$`)
var digitre = regexp.MustCompile(`^[[:digit:]]+$`)
var alphare = regexp.MustCompile(`^[[:alpha:]]+$`)
var alnumre = regexp.MustCompile(`^[[:alnum:]]+$`)
type List []interface{}
type Dict map[interface{}]interface{}
type Scope struct {
Names map[string]interface{}
Parent *Scope
continuing bool
breaking bool
returning bool
test *bool
}
type Builtin struct {
Arity int
Code func (*Scope, ...interface{}) (interface{}, error)
}
type Closure struct {
Arglist []string
Code List
*Scope
}
type Error struct {
Data interface{}
}
func (self Error) Error() string {
return fmt.Sprint(self.Data)
}
func FmtError(msg string, data interface{}) Error {
return Error{fmt.Sprintf("%s %v", msg, data)}
}
func (self List) Len() int { return len(self) }
func (self List) Swap(a, b int) { self[a], self[b] = self[b], self[a] }
func (self List) Less(a, b int) bool {
switch item1 := self[a].(type) {
case bool:
switch item2 := self[b].(type) {
case bool: return (!item1) && item2
default: panic(Error{fmt.Sprintf(
"Can't compare %T to %T.", item1, item2)})
}
case int:
switch item2 := self[b].(type) {
case int: return item1 < item2
case float64: return float64(item1) < item2
default: panic(Error{fmt.Sprintf(
"Can't compare %T to %T.", item1, item2)})
}
case float64:
switch item2 := self[b].(type) {
case int: return item1 < float64(item2)
case float64: return item1 < item2
default: panic(Error{fmt.Sprintf(
"Can't compare %T to %T.", item1, item2)})
}
case string:
switch item2 := self[b].(type) {
case string: return item1 < item2
default: panic(Error{fmt.Sprintf(
"Can't compare %T to %T.", item1, item2)})
}
default:
panic(Error{fmt.Sprintf(
"No comparisons defined on %T.", item1)})
}
}
// Equal complements sort.Interface to enable all comparison operators.
func (self List) Equal(a, b int) bool {
if self[a] == nil && self[b] == nil { return true }
if self[a] == nil || self[b] == nil { return false }
switch item1 := self[a].(type) {
case int:
switch item2 := self[b].(type) {
case int: return item1 == item2
case float64: return float64(item1) == item2
default: panic(Error{fmt.Sprintf(
"Can't compare %T to %T.", item1, item2)})
}
case float64:
switch item2 := self[b].(type) {
case int: return item1 == float64(item2)
case float64: return item1 == item2
default: panic(Error{fmt.Sprintf(
"Can't compare %T to %T.", item1, item2)})
}
default:
return self[a] == self[b]
}
}
func (self *Scope) Get(name string) (interface{}, error) {
if value, ok := self.Names[name]; ok {
return value, nil
} else if self.Parent != nil {
return self.Parent.Get(name)
} else {
return nil, Error{"Undefined variable: " + name}
}
}
func (self *Scope) SafeGet(name string, fallback interface{}) interface{} {
if value, ok := self.Names[name]; ok {
return value
} else if self.Parent != nil {
return self.Parent.SafeGet(name, fallback)
} else {
return fallback
}
}
func (self *Scope) Put(name string, value interface{}) {
if _, ok := self.Names[name]; ok {
self.Names[name] = value
} else if self.Parent != nil {
self.Parent.Put(name, value)
} else {
self.Names[name] = value
}
}
func (self *Closure) Apply(args ...interface{}) (interface{}, error) {
locals := Scope{Names: map[string]interface{}{}, Parent: self.Scope}
if len(self.Arglist) != len(args) {
return nil, Error{fmt.Sprintf(
"%d arguments passed to function expecting %d.",
len(args), len(self.Arglist))}
}
for i, n := range(self.Arglist) {
locals.Names[n] = args[i]
}
return Run(self.Code, &locals)
}
func (self Closure) String() string {
return fmt.Sprintf("fn %v do %v end", self.Arglist, self.Code)
}
func EvalNext(code List, cursor int, scope *Scope) (interface{}, int, error) {
collectArgs := func (num int, msg string) (List, error) {
args := make(List, num)
for i := 0; i < num; i++ {
if cursor >= len(code) {
return args, Error{msg}
}
tmp, csr, err := EvalNext(code, cursor, scope)
if err != nil {
return args, err
}
args[i] = tmp
cursor = csr
}
return args, nil
}
value := code[cursor]
switch value := value.(type) {
case Builtin:
cursor++
args, err := collectArgs(value.Arity, "Not enough arguments.")
if err != nil {
return nil, cursor, err
}
tmp, err := value.Code(scope, args...)
return tmp, cursor, err
case string:
if value[0] == ':' {
// Expect name to be already lowercased.
tmp, err := scope.Get(value[1:])
return tmp, cursor + 1, err
} else if value == "do" {
return ScanBlock(code, cursor + 1)
} else {
closure := scope.SafeGet(
strings.ToLower(value), value)
if closure, ok := closure.(Closure); ok {
cursor++
args, err := collectArgs(
len(closure.Arglist),
"Not enough arguments to " +
strings.ToLower(value))
if err != nil {
return nil, cursor, err
}
tmp, err := closure.Apply(args...)
return tmp, cursor, err
} else {
return value, cursor + 1, nil
}
}
default:
return value, cursor + 1, nil
}
return nil, 0, nil
}
func ScanBlock(code List, cursor int) (List, int, error) {
block := make(List, 0, len(code) - cursor)
for code[cursor] != "end" {
if code[cursor] == "do" {
tmp, csr, err := ScanBlock(code, cursor + 1)
if err != nil {
return block, csr, err
}
block = append(block, tmp)
cursor = csr
} else {
block = append(block, code[cursor])
cursor++
}
if cursor >= len(code) {
return block, cursor, Error{
"Unexpected end of input in block."}
}
}
return block, cursor + 1, nil
}
func Parse(words []string, context map[string]Builtin) (List, error) {
code := make([]interface{}, 0, len(words))
var buf List = nil
in_list := false
for _, i := range(words) {
lower := strings.ToLower(i)
if in_list {
if strings.HasSuffix(i, "]") {
if len(i) > 1 {
buf = append(buf, i[:len(i) - 1])
}
code = append(code, buf)
in_list = false
} else {
buf = append(buf, i)
}
} else if i == "[]" {
code = append(code, make(List, 0))
} else if strings.HasPrefix(i, "[") {
if strings.HasSuffix(i, "]") {
code = append(code, List{i[1:len(i) - 1]})
} else {
buf = List(make([]interface{}, 0))
if len(i) > 1 {
buf = append(buf, i[1:])
}
in_list = true
}
} else if strings.HasPrefix(i, "--") {
break
} else if strings.HasPrefix(i, ":") {
code = append(code, lower)
} else if lower == "do" || lower == "end" {
code = append(code, lower)
} else if lower == "true" {
code = append(code, true)
} else if lower == "false" {
code = append(code, false)
} else if lower == "nil" {
code = append(code, nil)
} else if proc, ok := context[lower]; ok {
code = append(code, proc)
} else if intre.MatchString(i) {
value, err := strconv.Atoi(i)
if err == nil {
code = append(code, value)
} else {
code = append(code, 0)
}
} else {
value, err := strconv.ParseFloat(i, 64)
if err == nil {
code = append(code, value)
} else {
code = append(code, i)
}
}
}
if in_list {
return List(code), FmtError(
"Unclosed list at end of line:", words)
} else {
return List(code), nil
}
}
// Run underlies most other control structures.
func Run(code List, scope *Scope) (interface{}, error) {
cursor := 0
for cursor < len(code) {
value, csr, err := EvalNext(code, cursor, scope)
if err != nil {
return nil, err
} else if scope.continuing || scope.breaking {
return nil, nil
} else if scope.returning {
return value, nil
} else if value != nil {
return value, FmtError(
"You don't say what to do with:", value)
}
cursor = csr
}
return nil, nil
}
// Results underlies while, ifelse and the command line.
func Results(code List, scope *Scope) (List, error) {
values := make([]interface{}, 0, len(code))
cursor := 0
for cursor < len(code) {
val, csr, err := EvalNext(code, cursor, scope)
if err != nil {
return List(values), err
} else if scope.returning {
return List{val}, nil
} else if scope.breaking || scope.continuing {
break
}
values = append(values, val)
cursor = csr
}
return List(values), nil
}
func Load(fn string, ctx map[string]Builtin, s *Scope) (interface{}, error) {
code := make([]interface{}, 0)
file, err := os.Open(fn)
if err != nil { return nil, err }
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if len(line) == 0 { continue }
words := splitre.Split(line, -1)
tokens, err := Parse(words, ctx)
if err != nil { return nil, err }
code = append(code, tokens...)
}
if scanner.Err() == nil {
return Run(List(code), s)
} else {
return nil, scanner.Err()
}
}
// Catch runs some code and traps any regular error or panic in a variable.
func Catch(varname string, code List, scope *Scope) (interface{}, error) {
varname = strings.ToLower(varname)
defer func () {
if err := recover(); err != nil {
scope.Names[varname] = fmt.Sprint(err)
}
}()
value, err := Run(code, scope)
if err != nil {
scope.Names[varname] = err.Error()
} else {
scope.Names[varname] = nil
}
if scope.returning {
return value, nil
} else {
return nil, nil
}
}
func PrintList(list List) {
fmt.Fprintln(Outs, strings.Join(StringSlice(list), " "))
}
func TypeList(list List) {
fmt.Fprint(Outs, strings.Join(StringSlice(list), " "))
}
// Readword returns a line of input from stdin without any processing.
func Readword() (string, error) {
scanner := bufio.NewScanner(Ins)
if scanner.Scan() {
return scanner.Text(), nil
} else if err := scanner.Err(); err != nil {
return "", err
} else {
return "", bufio.ErrFinalToken
}
}
// While loop.
func While(cond, code List, scope *Scope) (interface{}, error) {
for {
test, err := Results(cond, scope)
if err != nil { return nil, err }
if !ToBool(test[0]) { return nil, nil }
value, err := Run(code, scope)
if err != nil {
return nil, err
} else if scope.returning {
return value, nil
} else if scope.continuing {
scope.continuing = false
} else if scope.breaking {
scope.breaking = false
break
}
}
return nil, nil
}
// For loop; the variable is always treated as local.
func For(v string, i, l, p float64, code List, s *Scope) (interface{}, error) {
v = strings.ToLower(v)
s.Names[v] = i
if l >= i {
for i <= l {
value, err := Run(code, s)
if err != nil {
return nil, err
} else if s.returning {
return value, nil
} else if s.continuing {
s.continuing = false
} else if s.breaking {
s.breaking = false
break
}
i += p
s.Names[v] = i
}
} else {
for i >= l {
value, err := Run(code, s)
if err != nil {
return nil, err
} else if s.returning {
return value, nil
} else if s.continuing {
s.continuing = false
} else if s.breaking {
s.breaking = false
break
}
i += p
s.Names[v] = i
}
}
return nil, nil
}
// Foreach loop; the variable is always treated as local.
func Foreach(v string, items, code List, s *Scope) (interface{}, error) {
v = strings.ToLower(v)
for _, i := range(items) {
s.Names[v] = i
value, err := Run(code, s)
if err != nil {
return nil, err
} else if s.returning {
return value, nil
} else if s.continuing {
s.continuing = false
} else if s.breaking {
s.breaking = false
break
}
}
return nil, nil
}
// Fn creates a closure over the current scope and returns it.
func Fn(arglist []string, code List, scope *Scope) Closure {
for i, arg := range(arglist) {
arglist[i] = strings.ToLower(arg)
}
return Closure{arglist, code, scope}
}
// Function defines a named function in the current scope.
func Function(name string, arglist []string, code List, scope *Scope) {
scope.Names[strings.ToLower(name)] = Fn(arglist, code, scope)
}
// Map maps a user-defined function to the given argument list.
func Map(closure Closure, args List) (List, error) {
results := List(make([]interface{}, len(args)))
for i, arg := range(args) {
val, err := closure.Apply(arg)
if err != nil {
return results, err
} else {
results[i] = val
}
}
return results, nil
}
// Filter filters the given argument list by a user-defined function.
func Filter(closure Closure, args List) (List, error) {
results := List(make([]interface{}, 0, len(args)))
for _, arg := range(args) {
val, err := closure.Apply(arg)
if err != nil {
return results, err
} else if ToBool(val) {
results = append(results, arg)
}
}
return results, nil
}
// Add adds two numbers, preserving the type if at all possible.
func Add(a, b interface{}) interface{} {
switch t1 := a.(type) {
case int:
switch t2 := b.(type) {
case int: return t1 + t2
case float64: return float64(t1) + t2
default: return math.NaN()
}
case float64:
switch t2 := b.(type) {
case int: return t1 + float64(t2)
case float64: return t1 + t2
default: return math.NaN()
}
default:
return math.NaN()
}
}
// Sub subtracts two numbers, preserving the type if at all possible.
func Sub(a, b interface{}) interface{} {
switch t1 := a.(type) {
case int:
switch t2 := b.(type) {
case int: return t1 - t2
case float64: return float64(t1) - t2
default: return math.NaN()
}
case float64:
switch t2 := b.(type) {
case int: return t1 - float64(t2)
case float64: return t1 - t2
default: return math.NaN()
}
default:
return math.NaN()
}
}
// Mul multiplies two numbers, preserving the type if at all possible.
func Mul(a, b interface{}) interface{} {
switch t1 := a.(type) {
case int:
switch t2 := b.(type) {
case int: return t1 * t2
case float64: return float64(t1) * t2
default: return math.NaN()
}
case float64:
switch t2 := b.(type) {
case int: return t1 * float64(t2)
case float64: return t1 * t2
default: return math.NaN()
}
default:
return math.NaN()
}
}
func First(value interface{}) (interface{}, error) {
switch seq := value.(type) {
case List:
if len(seq) > 0 {
return seq[0], nil
} else {
return nil, Error{"First got an empty list."}
}
case string:
if len(seq) > 0 {
return seq[0:1], nil
} else {
return nil, Error{"First got an empty string."}
}
default:
return nil, FmtError("First expects a sequence, got:", value)
}
}
func Last(value interface{}) (interface{}, error) {
switch seq := value.(type) {
case List:
if len(seq) > 0 {
return seq[len(seq) - 1], nil
} else {
return nil, Error{"Last got an empty list."}
}
case string:
if len(seq) > 0 {
return seq[len(seq) - 1:len(seq)], nil
} else {
return nil, Error{"Last got an empty string."}
}
default:
return nil, FmtError("Last expects a sequence, got:", value)
}
}
func ButFirst(value interface{}) (interface{}, error) {
switch seq := value.(type) {
case List:
if len(seq) > 0 {
return seq[1:], nil
} else {
return nil, Error{"ButFirst got an empty list."}
}
case string:
if len(seq) > 0 {
return seq[1:], nil
} else {
return nil, Error{"ButFirst got an empty string."}
}
default:
return nil, FmtError(
"ButFirst expects a sequence, got:", value)
}
}
func ButLast(value interface{}) (interface{}, error) {
switch seq := value.(type) {
case List:
if len(seq) > 0 {
return seq[0:len(seq) - 1], nil
} else {
return nil, Error{"ButLast got an empty list."}
}
case string:
if len(seq) > 0 {
return seq[0:len(seq) - 1], nil
} else {
return nil, Error{"ButLast got an empty string."}
}
default:
return nil, FmtError(
"ButLast expects a sequence, got:", value)
}
}
func Sorted(seq List) List {
sorted := List(make([]interface{}, len(seq)))
copy(sorted, seq)
sort.Sort(sorted)
return sorted
}
func Fput(item interface{}, seq List) List {
ext := List(make([]interface{}, 0, len(seq) + 1))
ext = append(ext, item)
ext = append(ext, seq...)
return ext
}
func Lput(item interface{}, seq List) List {
ext := List(make([]interface{}, len(seq) + 1))
copy(ext, seq)
ext[len(ext) -1] = item
return ext
}
func Pick(value interface{}) (interface{}, error) {
switch seq := value.(type) {
case List:
if len(seq) > 0 {
return seq[rand.Intn(len(seq))], nil
} else {
return nil, Error{"Pick got an empty list."}
}
case string:
if len(seq) > 0 {
pos := rand.Intn(len(seq))
return seq[pos:pos + 1], nil
} else {
return nil, Error{"Pick got an empty string."}
}
default:
return nil, FmtError("Pick expects a sequence, got:", value)
}
}
func SetItem(index int, seq List, item interface{}) {
if index < 0 {
index = len(seq) + index
}
seq[index] = item
}
func Split(word string) List {
words := splitre.Split(strings.TrimSpace(word), -1)
if len(words) == 1 && words[0] == "" {
return List{}
} else {
return StringList(words)
}
}
func Copy(a interface{}) interface{} {
switch data := a.(type) {
case List:
cp := List(make([]interface{}, len(data)))
copy(cp, data)
return cp
case Dict:
cp := make(map[interface{}]interface{}, len(data))
for k, v := range(data) {
cp[k] = v
}
return Dict(cp)
default: return data
}
}
func Concat(seq1, seq2 List) List {
cat := List(make([]interface{},
len(seq1), len(seq1) + len(seq2)))
copy(cat, seq1)
cat = append(cat, seq2...)
return cat
}
func Iseq(init, limit int) List {
if init <= limit {
seq := List(make([]interface{}, 0, limit - init + 1))
for i := init; i <= limit; i++ {
seq = append(seq, i)
}
return seq
} else {
seq := List(make([]interface{}, 0, init - limit + 1))
for i := init; i >= limit; i-- {
seq = append(seq, i)
}
return seq
}
}
func ToBool(input interface{}) bool {
if input == nil { return false }
switch input := input.(type) {
case bool: return input
case int: return input != 0
case float64: return input != 0
default: panic(Error{fmt.Sprintf(
"Can't convert %#v to bool.", input)})
}
}
func ToString(input interface{}) string {
switch input := input.(type) {
case string: return input
default: return fmt.Sprint(input)
}
}
func ParseFloat(input interface{}) float64 {
switch input := input.(type) {
case float64: return float64(input)
case int: return float64(input)
case string:
value, err := strconv.ParseFloat(input, 64)
if err == nil {
return value
} else {
return math.NaN()
}
default: return math.NaN()
}
}
func ParseInt(input interface{}) int {
switch input := input.(type) {
case float64: return int(input)
case int: return int(input)
case string:
value, err := strconv.Atoi(input)
if err == nil {
return value
} else {
panic(Error{fmt.Sprintf(
"Can't convert %#v to int.", input)})
}
default: panic(Error{fmt.Sprintf(
"Can't convert %#v to int.", input)})
}
}
func StringSlice(input List) []string {
if input == nil { return nil }
output := make([]string, len(input))
for i, val := range(input) {
output[i] = ToString(val)
}
return output
}
func StringList(input []string) List {
if input == nil { return nil }
output := List(make([]interface{}, len(input)))
for i, val := range(input) {
output[i] = val
}
return output
}
func Substring(init, limit int, seq string) string {
if limit < 0 {
limit = len(seq) + limit
}
return seq[init:limit]
}
func Sublist(init, limit int, seq List) List {
if limit < 0 {
limit = len(seq) + limit
}
return seq[init:limit]
}
// NewDict returns a new dictionary off a list of alternating keys and values.
func NewDict(init List) Dict {
dictionary := Dict{}
i := 0
for i < len(init) {
key := init[i]
i++
if i < len(init) {
dictionary[key] = init[i]
} else {
dictionary[key] = nil
}
i++
}
return dictionary
}
func DictKeys(dict Dict) List {
keys := List(make([]interface{}, 0, len(dict)))
for i := range(dict) {
keys = append(keys, i)
}
return keys
}
var Procedures = map[string]Builtin {
"run": {1, func (s *Scope, a ...interface{}) (interface{}, error) {
if code, ok := a[0].(List); ok {
return Run(code, s)
} else {
return nil, FmtError(
"Run expects a list, found:", a[0])
}
}},
"results": {1, func (s *Scope, a ...interface{}) (interface{}, error) {
if code, ok := a[0].(List); ok {
return Results(code, s)
} else {
return nil, FmtError(
"Results expects a list, found:", a[0])
}
}},
"ignore": {1, func (s *Scope, a ...interface{}) (interface{}, error) {
if s.returning {
return a[0], nil
} else {
return nil, nil
}
}},
"catch": {2, func (s *Scope, a ...interface{}) (interface{}, error) {
code := a[1].(List)
return Catch(ToString(a[0]), code, s)
}},
"throw": {1, func (s *Scope, a ...interface{}) (interface{}, error) {
return nil, Error{a[0]}
}},
"break": {0, func (s *Scope, a ...interface{}) (interface{}, error) {
s.breaking = true
return nil, nil
}},
"continue": {0,
func (s *Scope, a ...interface{}) (interface{}, error) {
s.continuing = true
return nil, nil
}},
"return": {1, func (s *Scope, a ...interface{}) (interface{}, error) {
s.returning = true
return a[0], nil
}},
"print": {1, func (s *Scope, a ...interface{}) (interface{}, error) {
switch value := a[0].(type) {
case List: PrintList(value)
default: fmt.Fprintln(Outs, value)
}
return nil, nil
}},
"type": {1, func (s *Scope, a ...interface{}) (interface{}, error) {
switch value := a[0].(type) {
case List: TypeList(value)
default: fmt.Fprint(Outs, value)
}
return nil, nil
}},
"show": {1, func (s *Scope, a ...interface{}) (interface{}, error) {
fmt.Fprintln(Outs, a[0])
return nil, nil
}},
"readword": {0,
func (s *Scope, a ...interface{}) (interface{}, error) {
word, err := Readword()
if err == bufio.ErrFinalToken {
return nil, nil
} else {
return word, err
}
}},
"readlist": {0,
func (s *Scope, a ...interface{}) (interface{}, error) {
word, err := Readword()
if err == bufio.ErrFinalToken {
return nil, nil
} else if err == nil {
return Split(word), nil
} else {
return List{}, err
}
}},
"make": {2, func (s *Scope, a ...interface{}) (interface{}, error) {
varname := ToString(a[0])
s.Put(strings.ToLower(varname), a[1])
return nil, nil
}},
"local": {1, func (s *Scope, a ...interface{}) (interface{}, error) {
switch name := a[0].(type) {
case List:
for _, i := range(name) {
tmp := strings.ToLower(ToString(i))
s.Names[tmp] = nil
}
default: s.Names[strings.ToLower(ToString(name))] = nil
}
return nil, nil
}},
"localmake": {2,
func (s *Scope, a ...interface{}) (interface{}, error) {
varname := ToString(a[0])
s.Names[strings.ToLower(varname)] = a[1]
return nil, nil
}},
"thing": {1, func (s *Scope, a ...interface{}) (interface{}, error) {
varname := ToString(a[0])
return s.Get(strings.ToLower(varname))
}},
"if": {2, func (s *Scope, a ...interface{}) (interface{}, error) {
cond := ToBool(a[0])