Underload/a interpreter in python
Jump to navigation
Jump to search
def run(p): stack=[] program=p while program: x,program=program[0],program[1:] if x=='*':b,a=stack.pop(),stack.pop();stack.append(a+b) if x=='^':program=stack.pop()+program if x=='~':a,b=stack.pop(),stack.pop();stack.append(a);stack.append(b) if x==':':stack.append(stack[-1]) if x=='!':stack.pop() if x=='a':stack.append(f'({stack.pop()})') if x=='S':print(stack.pop(),end='') if x=='(': i=1;tmp='' while True: x,program=program[0],program[1:] if x=='(':i+=1 if x==')':i-=1 if i==0:break tmp+=x stack.append(tmp) program=r''' ( x y pair = (x y) pair = ~a~a* (x y) left = x left = ^! (x y) right = y right = ^~! )! ( x y true^ = x true = (!) x y false^ = y false = (~!) c t f if = t f c^^ if = a(a(a)~(a))~(a(a*~(^^)**^)****^)**^ true not = false false not = true x not = false true x ^ not = a((~!)(!))~(^)**^ )! ( zero = pair true () = ((!)()) zero isZero = true non_zero isZero = false isZero = left = ^! x succ = pair false x = ((~!) x) succ = a((~!))~* zero pred = zero non_zero pred = non_zero right pred = a:((((!)()))~(^~!))~(a(^!^)****^)**^ )! ( init cond step loop = init (init cond^ is false) init cond step loop = init step^cond step loop (init cond^ is true) loop = a(a(~:a)~(a(^)*~:(a)))~(a(a(a(^~:^)**(!))**~(a*a(a(a)~(a))~(a(a*~(^^)**^)****^)**^)****^)****:^)**^ x toUnary = (1...1) (repeat x times) toUnary = ()pair(left isZero not)(λx.x left right x right (1)* pair)loop right = ()~a~a*(^!^!a((~!)(!))~(^)**^)(:a(^!^~!)~(^~!(1)*~a~a*)**^)a(a(~:a)~(a(^)*~:(a)))~(a(a(a(^~:^)**(!))**~(a*a(a(a)~(a))~(a(a*~(^^)**^)****^)**^)****^)****:^)**^^~! )! ((!)()) a((~!))~* a((~!))~* a((~!))~* ()~a~a*(^!^!a((~!)(!))~(^)**^)(:a(^!^~!)~(^~!(1)*~a~a*)**^)a(a(~:a)~(a(^)*~:(a)))~(a(a(a(^~:^)**(!))**~(a*a(a(a)~(a))~(a(a*~(^^)**^)****^)**^)****^)****:^)**^^~! aS ''' run(program) #(111)
Or if you want to run it online.