This repository has been archived by the owner on May 30, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.py
3095 lines (2361 loc) · 77.8 KB
/
functions.py
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
import re
import sys
from types import (
IntType, FloatType, LongType, StringType, TupleType,
ListType, FileType, BooleanType, FunctionType)
import defs # NOQA
from cat.namespace import NameSpace
class Functions:
"""Return a function for a given symbol. Also maintains
a list of user defined functions."""
def __init__(self, userfunctions=None):
"""Constructor"""
if userfunctions is None:
userfunctions = {}
# Initial map of symbols to functions
# (as well as the methods defined on this class)
self.loadList = []
self.userNS = 'user'
self.NSdict = {'std':
{
'=': 'eq',
'!=': 'neq',
'<': 'lt',
'>': 'gt',
'<=': 'lteq',
'>=': 'gteq',
'if': '_if',
'~': '_not',
'!': '_saveVar',
'@': '_fetchVar',
'&': 'bit_and',
'|': 'bit_or',
'~': 'bit_not',
'del': '_del_word',
'type': 'typeof',
'cd': 'focusNS',
'ls': '_udf',
'rm': '_del_word',
'ln': 'linkToNS',
'pwd': 'showUserNS',
'#allDefs': '_loadAllDefs',
'#allWords': '_showAllWords',
'#def': '_dumpdef',
'#dir': '_dir',
'#doc': '_show',
'#dump': '_dumpStack',
'#instance': '_instance',
'#info': '_info',
'#listFiles': '_listDefinitionFiles',
'#load': '_load',
'#prompt': '_newPrompt',
'#reload': '_reload',
'#udf': '_udf',
'#vars': '_showVars',
'#whereis': '_whereis',
'#words': '_words',
'__globals__': {'CatDefs': 'CatDefs/', 'prompt': 'Cat> '},
},
'user': {'__vars__': {}, '__links__': [], '__inst__': {}},
}
self.NSdict['user'].update(userfunctions)
self.NSdict['user'].update(NameSpace.as_dict())
self.parseDef = re.compile(r'define\s+(\S+)\s*(:\s*\(.*\))?\s*(\{\{.*\}\})?\s*(\{.*\})', re.DOTALL)
self._checkAliases()
def _checkAliases(self):
"""
Moving functions off this object using the @define decorator.
Want to make sure we haven't moved anything off this object without
declaring it elsewhere / etc.
"""
for field, alias in self.NSdict['std'].items():
if isinstance(alias, str) and not alias.endswith('NS'):
assert hasattr(self, alias), '%s expects %s on self' % (field, alias)
def getFunction(self, what):
"""Called by the interpreter to get a function named <what>.
As a name may be None we return a flag stating whether <what>
was defined, followed by it's definition.
"""
if not isinstance(what, basestring):
return False, None
# check 'std' namespace first then built-ins
if what in self.NSdict['std']:
# A method alias.
return True, getattr(self, self.NSdict['std'][what])
elif hasattr(self, what):
# A named method (a built-in).
return True, getattr(self, what)
else:
# search name spaces: 'user' then linked namespaces
search = [self.userNS] + self.NSdict[self.userNS]['__links__']
if '__vars__' in search:
search.remove('__vars__')
search.remove('__links__')
search.remove('__inst__')
for ns in search:
if what in self.NSdict[ns]:
return True, self.NSdict[ns][what][0]
return False, None
def setFunction(self, name, definition, descrip='', ns=''):
"""Called to *define* new functions"""
if ns == '':
ns = self.userNS
self.NSdict[ns][name] = [definition, descrip]
def isFunction(self, what):
'''
Returns True if the argument is defined as a function in
some user-related namespace; False otherwise
'''
if hasattr(self, what):
return True
search = ['std', self.userNS] + self.NSdict[self.userNS]['__links__']
if '__vars__' in search:
search.remove('__vars__')
search.remove('__links__')
search.remove('__inst__')
for ns in search:
if what in self.NSdict[ns]:
return True
return False
def getVar(self, what):
'''
returns the value associated with user variable named in what from the user's '__var__' dict
Note that 'what' may be of the form:
<simple name>
<namespace>:<simple name>
<namespace> may also be the special case 'global' to access global variables
'''
if what.count(":") == 1:
ns, var = what.split(":")
if ns.lower() == 'global':
if var in self.NSdict['std']['__globals__']:
return True, self.NSdict['std']['__globals__'][var]
else:
return False, None
else:
if ns in self.NSdict and var in self.NSdict[ns]['__vars__']:
return True, self.NSdict[ns]['__vars__'][var]
else:
return False, None
else:
search = [self.userNS] + self.NSdict[self.userNS]['__links__']
for ns in search:
if what in self.NSdict[ns]['__vars__']:
return True, self.NSdict[ns]['__vars__'][what]
if what in self.NSdict['std']['__globals__']:
return True, self.NSdict['std']['__globals__'][what]
else:
return False, None
def setVar(self, var, val):
'''
stores val into the __vars__ dictionary in some namespace under key name var
var may take the form:
<simple name>
<namespace>:<simple name>
Note that the namespace 'global' is reserved for saving global variables
'''
if var.count(":") == 1:
ns, var = var.split(":")
if ns.lower == 'global':
self.NSdict['std']['__globals__'][var] = val
else:
self.NSdict[ns]['__vars__'][var] = val
else:
self.NSdict[self.userNS]['__vars__'][var] = val
def _printList(self, cat, theList, across=5):
'''Print the elements in theList'''
if len(theList) == 0:
cat.output(" _none_", 'green')
return
longest = max([len(x) for x in theList])
i = 0
for name in theList:
l = longest + 2 - len(name)
fragment = " " + name + " " * l
cat.output(fragment, 'green')
i += 1
if i == across:
print
i = 0
if i > 0:
print
# Methods defining functions with invalid python names.
# They're prefixed with underscores so people don't unintentionally
# re-define them and so we can identify these when 'defs' is called
def _if(self, cat):
'''
if : (func:true_func func:false_func bool:condition -> any|none)
desc:
executes one predicate or another whether the condition is true
tags:
level0,control
'''
ffalse, ftrue, truth = cat.stack.pop_n(3)
if truth:
cat.stack.push(ftrue)
else:
cat.stack.push(ffalse)
self.eval(cat)
def _dumpStack(self, stack):
'''
#dump : (-- -> --)
desc:
non-destructively dumps the entire contents of the stack to the console
tags:
custom,console,stack
'''
stack.output(str(stack), 'green')
def _show(self, stack):
'''
#doc : (string:func_name -> --)
desc:
displays documentation for function whose name string is on top of the stack
A word name may be prefixed with a namespace. E.g. 'shuffle:abba #doc
tags:
custom,definitions,methods
'''
name = stack.pop().strip('"')
if name.count(":") == 1:
ns, name = name.split(":")
if name in self.NSdict[ns]:
obj = self.NSdict[ns][name]
stack.output(obj[1], 'green')
return
else:
raise ValueError("#doc: No documentation for '%s' in '%s'" % (name, ns))
if name in ['__vars__', '__links__', '__inst__']:
return
if name in self.NSdict['std']:
# get method's doc string
fcn = getattr(self, self.NSdict['std'][name])
stack.output(fcn.__doc__, 'green')
elif hasattr(self, name):
fcn = getattr(self, name)
stack.output(fcn.__doc__, 'green')
else:
search = [self.userNS] + self.NSdict[self.userNS]['__links__']
for ns in search:
if name in self.NSdict[ns]:
obj = self.NSdict[ns][name]
stack.output(obj[1], 'green')
return
stack.output("No description for " + name, 'red')
def _load(self, stack, force=False, ns=''):
'''
#load : (string:fileName -> --)
desc:
Loads the script whose name string is on top of the stack into a namespace
tags:
level0,control,system
'''
def stripComments(text):
temp = text.strip()
if temp == "" or temp.startswith('//') or temp.startswith('#'):
return ""
ix = temp.rfind('//')
if ix > 0:
temp = temp[:ix]
return temp
fileName = stack.pop()
if type(fileName) != StringType:
raise Exception("#load: File name must be a string")
if not force:
if fileName in self.loadList:
raise Warning("#load: The file of Cat definitions called '%s' has already been loaded. Skipping it." % fileName)
if ns == '':
ns = self.userNS
fd = open(fileName, 'r')
buffer = ""
lineNo = 0
inDef = False
for line in fd:
lineNo += 1
temp = stripComments(line.strip())
if temp == "":
continue
if not inDef:
if not temp.startswith("define"):
stack.eval(temp)
continue
else:
inDef = True
# must be in a definition (this hack permits 1-line definitions)
if inDef:
# consolidate lines of a definition into a single string
buffer += line # to preserve original formatting
# end of function definition?
if not temp.endswith("}}") and temp.endswith("}"):
# parse parts of the string
mo = self.parseDef.match(buffer)
if not mo:
raise ValueError("#load: Bad definition in file %s at line %d" % (fileName, lineNo))
# create definition
descrip = mo.group(3).strip("{}") if mo.group(3) else ''
effect = mo.group(2).strip(" :") if mo.group(2) else ''
lines = mo.group(4).strip("{}").split("\n")
buf = ""
# remove all comments from the definition
for temp in lines:
temp = stripComments(temp)
if temp != "":
buf += temp + " "
self.setFunction(mo.group(1), list(stack.gobble(buf)), " %s : %s\n%s" % (mo.group(1), effect, descrip), ns)
buffer = ""
inDef = False
self.loadList.append(fileName)
fd.close()
def _reload(self, stack):
'''
#reload : (string:fileName -> --)
desc:
Reloads the script whose name string is on top of the stack
tags:
level0,control,system
'''
self._load(stack, True)
def _loadAllDefs(self, stack):
'''
#allDefs : (-- -> --)
desc:
load all definitions into their corresponding namespaces
tags:
custom,namespaces,definitions
'''
loadFile = self.NSdict['std']['__globals__']['CatDefs'] + "everything.cat"
stack.push(loadFile)
self._load(stack)
def _dumpdef(self, stack):
'''
#def : (string:name -> --)
desc:
prints the definition string of the named function to the console
the function name may be prefixed with a <namespace>: if desired
Example: 'shuffle:abba #def
tags:
custom,console,debugging
'''
atom = stack.pop().strip('"')
if atom.count(":") == 1:
ns, name = atom.split(":")
obj = self.NSdict[ns][name]
stack.output(obj[0], 'green')
return
if hasattr(self, atom):
stack.output("Function %s is a primitive" % atom, 'green')
else:
defined, func = self.getFunction(atom)
if defined:
stack.output("%s: %s" % (atom, func), 'green')
else:
stack.output("Function %s is undefined" % atom, 'red')
def _instance(self, stack):
'''
#instance (string:name list:args|any:arg|nil string:module.class -> --)
desc:
creates an instance of a specified class
instance is invoked in the usual way: <instance>.<method>
Example: 'Meeus #import
'm nil 'Meeus.Meeus #instance
Use: [2012,7,4] m.JD
tags:
custom,instance
'''
cls, args, name = stack.pop_n(3)
if type(cls) != StringType:
raise ValueError("#instance: The module.class identifier must be a string")
if type(name) != StringType:
raise ValueError("#instance: The instance name must be a string")
if type(args) == StringType and args.startswith("["):
args = eval(args)
if type(args) in [ListType, TupleType]:
args = str(tuple(args))
else:
args = str((args,))
self.NSdict[self.userNS]['__inst__'][name] = eval("%s%s" % (cls, args), sys.modules)
def _saveVar(self, stack):
'''
! : (any string:userVarName ->)
desc:
saves the value at [-1] to the user symbol table
with the name provided by the string at [0]
tags:
custom,variables,user
'''
varName, value = stack.pop_2()
if self.isFunction(varName):
stack.push(value)
raise ValueError("!: User variable '%s' duplicates an existing method" % varName)
self.setVar(varName, value)
def _fetchVar(self, stack):
'''
@ : (string:userVarName -> val)
desc:
pushes the value of the named user-variable onto the stack
Note: the userVarName by itself (no quotes or @) will push its value onto the stack
tags:
custom,variables,user
'''
name = stack.pop()
defined, val = self.getVar(name)
if defined:
stack.push(val)
else:
raise KeyError("@: No variable called " + name)
def _showVars(self, stack):
'''
#vars : (-- -> --)
desc:
lists names of variables in the user and global symbol tables
tags:
custom,user_variables
'''
# variables in the default user namespace and in 'globals'
keys = self.NSdict[self.userNS]['__vars__'].keys()
keys.sort()
stack.output("User-defined variables in default namespace '%s':" % self.userNS, 'green')
self._printList(stack, keys)
keys = self.NSdict['std']['__globals__'].keys()
keys.sort()
stack.output("Variables defined in 'globals':", 'green')
self._printList(stack, keys)
search = self.NSdict[self.userNS]['__links__']
# search for variables in linked-in namespaces
for ns in search:
keys = self.NSdict[ns]['__vars__'].keys()
keys.sort()
stack.output("User-defined variables in namespace '%s':" % ns, 'green')
self._printList(stack, keys)
def _dir(self, stack):
'''
#dir : (string -> --)
desc:
displays the results of applying the Python 'dir' function
to the argument on top of the stack. Used to examine the content
of sys.modules.
tags:
custom,python,dir
'''
if stack.length() == 0:
arg = ''
else:
arg = str(stack.pop())
lst = eval("dir(eval('%s'))" % arg, sys.modules)
self._printList(stack, lst, 4)
def _words(self, stack, showAll=False):
'''
words: (-- -> --)
desc:
Prints a list of available words to the user's terminal
tags:
level2,words
'''
stack.output("Built-in (primitive) words:", 'green')
functions = self.NSdict['std'].keys()
for method in dir(self):
if method not in functions and not method.startswith('_'):
functions.append(method)
functions.remove('setFunction')
functions.remove('getFunction')
functions.remove('isFunction')
functions.remove('setVar')
functions.remove('getVar')
functions.remove('parseDef')
functions.remove('loadList')
functions.remove('userNS')
functions.remove('NSdict')
functions.sort()
self._printList(stack, functions)
if not showAll:
search = [self.userNS] + self.NSdict[self.userNS]['__links__']
else:
search = self.NSdict.keys()
search.remove('std')
search.sort()
for ns in search:
print
stack.output("Words defined in '%s' namespace:" % ns, 'green')
functions = self.NSdict[ns].keys()
functions.sort()
if '__vars__' in functions:
functions.remove('__vars__')
functions.remove('__links__')
functions.remove('__inst__')
self._printList(stack, functions)
print
def _showAllWords(self, stack):
'''
#allWords : (-- -> --)
desc:
Shows all defined words in all namespaces
tags:
custom,namespaces,words,functions
'''
self._words(stack, True)
def _info(self, stack):
'''
#info : (-- -> --)
desc:
lists modules available for use and other bits of useful information
tags:
custom,modules
'''
keys = sys.modules.keys()
keys.sort()
stack.output("**modules: " + str(keys), 'green')
keys = self.NSdict[self.userNS]['__inst__'].keys()
keys.sort()
stack.output("**instances: " + str(keys), 'green')
keys = self.NSdict[self.userNS]['__vars__'].keys()
keys.sort()
stack.output("**user-defined variables: " + str(keys), 'green')
def _udf(self, stack):
'''
Shows all user-defined functions
'''
keys = self.NSdict[self.userNS].keys()
keys.sort()
keys.remove('__vars__')
keys.remove('__links__')
keys.remove('__inst__')
self._printList(stack, keys)
print
def _del_word(self, stack):
'''
del : (string:name -> --)
desc:
deletes the definition of the word from the current user namespace
Note: the name may be of the form: word1,word2,... (e.g. 'test,junk,smmpt)
of a list (e.g. ['test 'junk 'smmpt] list
Words may have the form: <namespace>:<word>
tags:
level2,words
'''
top = stack.pop()
if type(top) == StringType:
words = [x for x in top.split(",") if x != '']
elif type(top) in [ListType, TupleType]:
words = top
else:
raise ValueError("del_word: expect a string or list")
for word in words:
if word in ['__vars__', '__links__', '__inst__']:
continue
elif word.count(":") == 1:
ns, wrd = word.split(":")
if wrd in ['__vars__', '__links__', '__inst__']:
continue
if ns == 'std':
continue
if ns in self.NSdict and wrd in self.NSdict[ns]:
del self.NSdict[ns][word]
elif word in self.NSdict[self.userNS]:
del self.NSdict[self.userNS][word]
def _listDefinitionFiles(self, stack):
'''
#listFiles : (string:path -> --)
desc:
lists the contents of all of the definition files in the
directory indicated by the path (string) on top of the stack
tags:
extension,definitions
'''
from glob import iglob
path = stack.pop()
if type(path) != StringType:
raise ValueError("#listFiles: Directory path must be a string")
fnmap = {}
path += "*.cat"
regex = re.compile(r'^\s*define\s+(\S+)')
for file in iglob(path):
fd = open(file, 'r')
for line in fd:
mo = regex.match(line)
if mo:
funcName = mo.group(1)
if funcName in fnmap:
stack.output("File %s duplicates function %s" % (file, funcName), 'red')
else:
fnmap[funcName] = file
fd.close()
keys = fnmap.keys()
keys.sort()
maxStr = max([len(x) for x in keys]) + 2
print
for key in keys:
akey = key.rjust(maxStr, " ")
stack.output(" %s -- %s" % (akey, fnmap[key]), 'green')
def _whereis(self, stack):
'''
#whereis : (string:word -> --)
desc:
Shows where the word (a string) is to be found:
built-in (primitive)
in a definition file
user defined
E.g. 'swap #whereis
tags:
extension,search,word
'''
from glob import iglob
theWord = stack.pop()
source = 'undefined'
defined = False
search = self.NSdict.keys()
for ns in search:
if theWord in self.NSdict[ns]:
if ns == 'std':
source = "built-in"
else:
source = ns
defined = True
break
if not defined and hasattr(self, theWord):
source = "built-in"
elif not defined:
path = self.NSdict['std']['__globals__']['CatDefs']
path += "*.cat"
# escape characters in theWord that are interpreted by "re"
letters = [x for x in theWord]
for i in range(len(letters)):
c = letters[i]
if c in ".[]{}^$*?()+-|": # regular expression characters
letters[i] = "\\" + c
theWord = "".join(letters)
# search the standard definition files
regex = re.compile(r'^\s*define\s+(%s)' % theWord)
found = False
for file in iglob(path):
if found:
break
fd = open(file, 'r')
for line in fd:
if regex.match(line.strip()):
source = file
found = True
break
fd.close()
if not found:
source = "undefined" % theWord
stack.output("%s: %s" % (theWord, source), 'green')
def _newPrompt(self, stack):
'''
#prompt : (string:prompt -> --)
desc:
Sets the prompt string to the string on top of the stack
tags:
console
'''
self.NSdict['std']['__globals__']['prompt'] = str(stack.pop())
# Now begins methods implementing functions with non-conflicting acceptable Python names
def zip(self, stack):
'''
zip : (list list -> list)
desc:
creates a list of paired objects from the two lists on
top of the stack.
tags:
custom,lists
'''
r, l = stack.pop_2()
stack.push([list(x) for x in zip(l, r)])
def unzip(self, stack):
'''
unzip : (list -> list:left list:right)
desc:
unzips the list on top of the stack to a pair of lists that
are then pushed onto the stack. The first element of each
of the pairs within the argument list goes into the left list
and the second into the right list.
tags:
custom,lists
'''
lst = stack.pop()
lst = zip(*lst)
stack.push(list(lst[0]))
stack.push(list(lst[1]))
def split(self, stack):
'''
split : (string:target string:splitter -> list)
desc:
splits a target string into segments based on the 'splitter' string
tags:
custom,strings
'''
splitter, target = stack.pop_2()
if type(target) != StringType or type(splitter) != StringType:
raise ValueError("split: Both arguments must be strings")
if len(splitter) == 0:
stack.push([x for x in target])
else:
stack.push(target.split(splitter))
def join(self, stack):
'''
join : (list string:connector -> string)
desc:
joins together the elements of the list at [-1] using the connector
string at [0].
tags:
custom,strings,lists
'''
conn, lst = stack.pop_2()
if type(conn) != StringType:
conn = str(conn)
result = ''
for item in lst:
result += str(item) + conn
stack.push(result.rstrip(conn))
def count_str(self, stack):
'''
count_str : (string:target string:test -> string:target int)
desc:
counts the number of non-overlapping occurrences of the test string at [0]
found in the target string at [-1]
tags:
custom,strings
'''
test, target = stack.pop_2()
if type(test) != StringType or type(target) != StringType:
raise ValueError("count_str: Both target and test objects must be strings")
stack.push(target)
stack.push(target.count(test))
def eq(self, stack):
"""
eq : (any any -> bool)
desc:
returns True if top two items on stack have the same value; otherwise False
tags:
level1,comparison"
"""
a, b = stack.pop_2()
stack.push(a == b)
def neq(self, stack):
"""
neq : (any any -> bool)
desc:
returns True if top two items on stack have differning values; otherwise False
tags:
level1,comparison"
"""
a, b = stack.pop_2()
stack.push(a != b)
def gt(self, stack):
"""
gt : (any any -> bool)
desc:
returns True if the value at [-1] is greater than the one at [0];
otherwise False
tags:
level1,comparison"
"""
a, b = stack.pop_2()
stack.push(b > a)
def lt(self, stack):
"""
lt : (any any -> bool)
desc:
returns True if the object at [-1] is less than the one at [0];
otherwise False
tags:
level1,comparison"
"""