π/compile from Minsky machine
Jump to navigation
Jump to search
This python program compiles Minsky machine program into π program.(Using state 0 means halt,and the program starts from state 1.)
program=''' inc a 2 inc a 3 inc a 4 inc b 5 dec a 4 0 ''' s=lambda x,y:f'π©/{x}\\/{y}\\' g=lambda x:f'π¨/{x}\\' loop=lambda c,b:'{'+f'{b}'+'}'+f'{c}' seq=lambda*x:''.join(x) add=lambda x,y:f'β/{x}\\/{y}\\' sub=lambda x,y:f'β/{x}\\/{y}\\' If=lambda flag,c,t:seq(s(flag,c),loop(g(flag),seq(t,s(flag,0)))) ifEq=lambda x,y,c:If('flag1',add(sub(1,x),y),If('flag2',add(sub(1,y),x),c)) n=lambda x:sub(1,x) inc=lambda x,y:seq(s(x,add(g(x),1)),s('c',y)) dec=lambda x,y,z:seq(If('flag3',g('c'),seq(s(x,sub(g(x),1)),s('c',y))),If('flag3',n(g('c')),s('c',z))) o=lambda x:f'π/{x}\\' def compile(program): p=[[x for x in x.split(' ') if x in{'inc','dec','a','b'}or x.isdigit()] for x in program.split('\n')if x!=''] i=1;a,b,c='abc' res=seq(s(a,0),s(b,0),s(c,1),'{') for x in p: if(x[0],x[1])==('inc','a'): res+=ifEq(g(c),i,inc(a,x[2])) if(x[0],x[1])==('inc','b'): res+=ifEq(g(c),i,inc(b,x[2])) if(x[0],x[1])==('dec','a'): res+=ifEq(g(c),i,dec(b,x[2],x[3])) if(x[0],x[1])==('dec','b'): res+=ifEq(g(c),i,dec(b,x[2],x[3])) i+=1 res+=seq('}',g(c),o('"a:"'),o(g(a)),o('";b:"'),o(g(b))) return res print(compile(program))
For this example,the output will be:
π©/a\/0\π©/b\/0\π©/c\/1\{π©/flag1\/β/β/1\/π¨/c\\\/1\\{π©/flag2\/β/β/1\/1\\/π¨/c\\\{π©/a\/β/π¨/a\\/1\\π©/c\/2\π©/flag2\/0\}π¨/flag2\π©/flag1\/0\}π¨/flag1\π©/flag1\/β/β/1\/π¨/c\\\/2\\{π©/flag2\/β/β/1\/2\\/π¨/c\\\{π©/a\/β/π¨/a\\/1\\π©/c\/3\π©/flag2\/0\}π¨/flag2\π©/flag1\/0\}π¨/flag1\π©/flag1\/β/β/1\/π¨/c\\\/3\\{π©/flag2\/β/β/1\/3\\/π¨/c\\\{π©/a\/β/π¨/a\\/1\\π©/c\/4\π©/flag2\/0\}π¨/flag2\π©/flag1\/0\}π¨/flag1\π©/flag1\/β/β/1\/π¨/c\\\/4\\{π©/flag2\/β/β/1\/4\\/π¨/c\\\{π©/b\/β/π¨/b\\/1\\π©/c\/5\π©/flag2\/0\}π¨/flag2\π©/flag1\/0\}π¨/flag1\π©/flag1\/β/β/1\/π¨/c\\\/5\\{π©/flag2\/β/β/1\/5\\/π¨/c\\\{π©/flag3\/π¨/c\\{π©/b\/β/π¨/b\\/1\\π©/c\/4\π©/flag3\/0\}π¨/flag3\π©/flag3\/β/1\/π¨/c\\\{π©/c\/0\π©/flag3\/0\}π¨/flag3\π©/flag2\/0\}π¨/flag2\π©/flag1\/0\}π¨/flag1\}π¨/c\π/"a:"\π/π¨/a\\π/";b:"\π/π¨/b\\