User:Jan jelo/SKA calculus interpreter
Jump to navigation
Jump to search
This is a stack-based SKA calculus interpreter in Python by User:Jan jelo.
def pop(x,l):
a=l.pop()
x.append(a)
if a==')':
i=1
while i:
a=l[-1]
x.append(l.pop())
if a=='(':i-=1
if a==')':i+=1
return
y=[];z=[]
while x:y.append(x.pop())
while y:z.append(y.pop())
while z:x.append(z.pop())
def op(l):
if len(l)==1:return l[0]
return l[-2]
def copy(x,y):
a=[]
while y:a.append(y.pop())
while a:x.append(a[-1]);y.append(a[-1]);a.pop()
def show(s):
res=''
for i in s:
if i in'()':continue
elif i=='s1':res+='as'
elif i=='s2':res+='aas'
elif i=='k1':res+='ak'
else:res+=i
return res
def val(x):
X=list(x)
R=[]
i=0
while X:
a=X.pop()
R.append(a)
if a=='a':i+=1
else:i-=1
if i!=-1:
raise Exception('The number of "a" does not match with the number of combinators')
while R:X.append(R.pop())
while X:
a=[]
pop(a,X)
if a[0]=='a':
A=[]
pop(A,R)
B=[]
pop(B,R)
o=op(A)
if o=='s':
X.append('(')
X.append('s1')
while B:X.append(B.pop())
X.append(')')
continue
if o=='s1':
A.pop()
A.pop()
tmp=[]
pop(tmp,A)
X.append('(')
X.append('s2')
while tmp:X.append(tmp.pop())
while B:X.append(B.pop())
X.append(')')
continue
if o=='s2':
A.pop()
A.pop()
tmp=[]
pop(tmp,A)
tmp2=[]
pop(tmp2,A)
X.append('a')
X.append('a')
tmp3=[];copy(tmp3,B)
while tmp:X.append(tmp.pop())
while B:X.append(B.pop())
X.append('a')
while tmp2:X.append(tmp2.pop())
while tmp3:X.append(tmp3.pop())
continue
if o=='k':
X.append('(')
X.append('k1')
while B:X.append(B.pop())
X.append(')')
continue
if o=='k1':
A.pop()
A.pop()
tmp=[]
pop(tmp,A)
while tmp:X.append(tmp.pop())
continue
else:
while a:R.append(a.pop())
return show(R)
exp='aaaskks'
print(val(exp))# s
exp='aaskk'
print(val(exp))# aaskk