Skip to content

Commit

Permalink
fix map, remove hex mode, add reduce, extend gcd to lists
Browse files Browse the repository at this point in the history
  • Loading branch information
Mego committed Apr 16, 2016
1 parent 3b49c37 commit 0cee3ca
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 53 deletions.
40 changes: 34 additions & 6 deletions SeriouslyCommands.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
#!/usr/bin/env python3

from fractions import gcd
try:
from math import gcd as _gcd
except:
from fractions import gcd as _gcd
import operator, cmath
import math as rmath
import random, itertools, sys, string, binascii, ast
Expand Down Expand Up @@ -48,6 +51,12 @@ def Fib(n):

def prod(iter):
return reduce(operator.mul, iter, 1)

def gcd(*vals):
if len(vals) == 2:
return _gcd(*vals)
else:
return _gcd(vals[0], gcd(*vals[1:]))

primes = [2,3]

Expand Down Expand Up @@ -86,8 +95,7 @@ def __init__(self, code):
raise TypeError

def __call__(self, srs):
c = binascii.hexlify(self.code) if srs.hex_mode else self.code
srs.eval(c, print_at_end=False)
return srs.eval(self.code)

def __str__(self):
return '{}'.format(self.code)
Expand Down Expand Up @@ -385,11 +393,13 @@ def M_fn(srs):
srs.push(max(a))
else:
b=srs.pop()
if srs.debug_mode:
print('mapping {} over {}'.format(a, b))
res=[]
for x in b:
s = srs.make_new(x)
a(s)
res+=s.stack
r = a(s)
res.extend(r)
srs.push(res)

def r_fn(srs):
Expand Down Expand Up @@ -745,10 +755,28 @@ def shuffle_fn(srs):
a = srs.pop()
random.shuffle(a)
srs.push(a)

def g_fn(srs):
a = srs.pop()
if isinstance(a, list):
srs.push(gcd(*a))
else:
b = srs.pop()
srs.push(gcd(a,b))

def reduce_fn(srs):
a = srs.pop()
if isinstance(a, list):
srs.push([x//gcd(*a) for x in a])
else:
b = srs.pop()
srs.push(b//gcd(a,b))
srs.push(a//gcd(a,b))

fn_table={
0x09:lambda x:x.push(sys.stdin.read(1)),
0x0C:lambda x:x.push(sys.stdin.read()),
0x1F:reduce_fn,
0x20:lambda x:x.push(len(x.stack)),
0x21:lambda x:x.push(math.factorial(x.pop())),
0x23:make_list_fn,
Expand Down Expand Up @@ -803,7 +831,7 @@ def shuffle_fn(srs):
0x64:deq_fn,
0x65:lambda x:x.push(math.exp(x.pop())),
0x66:f_fn,
0x67:lambda x:x.push(gcd(x.pop(),x.pop())),
0x67:g_fn,
0x68:lambda x:x.push(math.hypot(x.pop(),x.pop())),
0x69:i_fn,
0x6A:lambda x:x.push(str.join(x.pop(),list(map(str,x.pop())))),
Expand Down
64 changes: 32 additions & 32 deletions commands.txt
Original file line number Diff line number Diff line change
@@ -1,35 +1,35 @@
00 (NUL):
01 (SOH):
02 (STX):
03 (ETX):
04 (EOT):
05 (ENQ):
06 (ACK):
07 (bell):
08 (backspace):
09 (tab): push a single byte of unformatted input from STDIN (push sys.stdin.read(1))
0A (line feed):
0B (vertical tab):
0C (form feed): push all data from stdin as a string
0D (carriage return):
0E (SO):
0F (SI):
10 (DLE):
11 (DC1):
12 (DC2):
13 (DC3):
14 (DC4):
15 (NAK):
16 (SYN):
17 (ETB):
18 (CAN):
19 (EM):
1A (SUB):
1B (ESC):
1C (FS):
1D (GS):
1E (RS):
1F (US):
01 ():
02 ():
03 ():
04 ():
05 ():
06 ():
07 ():
08 ():
09 (): push a single byte of unformatted input from STDIN (push sys.stdin.read(1))
0A ():
0B (♂): take the next command and map it over the top of the stack (for example, ♂A is equivalent to `A`M)
0C (): push all data from stdin as a string
0D ():
0E ():
0F ():
10 ():
11 ():
12 ():
13 ():
14 ():
15 (§):
16 ():
17 ():
18 ():
19 ():
1A ():
1B ():
1C ():
1D ():
1E ():
1F (▼): pop a,b: push b//gcd(a,b),a//gcd(a,b); pop [a]: push [x//gcd([a]) for x in [a]]
20 ( ): push the # of elements on the stack (push len(stack))
21 (!): pop a: push a! (factorial(a))
22 ("): string literal, reads until next " and pushes value onto stack. An implied " is present at EOF if needed.
Expand Down Expand Up @@ -101,7 +101,7 @@
64 (d): pop [a]: dequeue b from [a], push [a],b
65 (e): pop a: push exp(a)
66 (f): pop a: push the Fibonacci index of a if a is a Fibonacci number, else -1; pop "a",[b]: push "a".format(*[b])
67 (g): pop a,b: push gcd(a,b)
67 (g): pop a,b: push gcd(a,b); pop [a]: push gcd([a])
68 (h): pop a,b: push sqrt(a*a+b*b) (Euclidean norm)
69 (i): pop "a": push atof(a); pop [a]: push each element from [a], starting from end (flatten)
6A (j): pop "a",[b]: push "a".join([b]) (converting values in [b] to strings with $ if necessary)
Expand Down
36 changes: 21 additions & 15 deletions seriously.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,12 @@ def _make_new(cls, init=None, debug_mode=False):

def make_new(self, *stack):
return self._make_new(init=list(stack), debug_mode=self.debug_mode)
return res

def __init__(self, init_stack=None, debug_mode=False, hex_mode=False):
def __init__(self, init_stack=None, debug_mode=False):
self.stack = init_stack if init_stack is not None else []
self.debug_mode = debug_mode
self.fn_table = SeriouslyCommands.fn_table
self.code = ''
self.hex_mode = hex_mode
self.preserve = False
self.pop_counter = 0

Expand Down Expand Up @@ -60,11 +58,6 @@ def clear_stack(self):
self.stack = list()

def eval(self, code):
if self.hex_mode:
tmp = ''
for i in range(0, len(code), 2):
tmp += chr_cp437(int(code[i:i+2], 16))
code = tmp
if self.debug_mode:
print(code)
i = 0
Expand Down Expand Up @@ -119,19 +112,35 @@ def eval(self, code):
elif c == '[':
l = ''
i += 1
while i < len(code) and code[i] != ']':
nest = 1
while i < len(code):
if code[i] == '[':
nest += 1
elif code[i] == ']':
nest -= 1
if nest == 0:
break
l += code[i]
i += 1
self.push(literal_eval('[{}]'.format(l)))
if self.debug_mode:
print("list: [{}]".format(l))
print(self.stack)
elif c == '`':
f = ''
i += 1
while i < len(code) and code[i] != '`':
f += code[i]
i += 1
if self.debug_mode:
print('fn: {}'.format(f))
self.push(SeriouslyCommands.SeriousFunction(f))
elif ord(c) in range(48, 58):
self.push(int(c))
elif ord_cp437(c) == 0x0B:
i += 1
self.push(SeriouslyCommands.SeriousFunction(code[i]))
self.fn_table.get(ord_cp437('M'))(self)
else:
if self.debug_mode:
print("{:2X}".format(ord_cp437(c)))
Expand All @@ -151,8 +160,8 @@ def eval(self, code):
return self.stack[::-1]


def srs_exec(debug_mode=False, file_obj=None, code=None, hex=False):
srs = Seriously(debug_mode=debug_mode, hex_mode=hex)
def srs_exec(debug_mode=False, file_obj=None, code=None):
srs = Seriously(debug_mode=debug_mode)
if file_obj:
for x in srs.eval(file_obj.read()):
print(x)
Expand All @@ -170,9 +179,6 @@ def ide_mode():
description="Run the Seriously interpreter")
parser.add_argument("-d", "--debug", help="turn on debug mode",
action="store_true")
parser.add_argument("-x", "--hex",
help="turn on hex mode (code is taken in hex values)",
action="store_true")
parser.add_argument("-i", "--ide",
help="disable unsafe commands", action="store_true")
group = parser.add_mutually_exclusive_group(required=True)
Expand All @@ -182,5 +188,5 @@ def ide_mode():
args = parser.parse_args()
if args.ide:
ide_mode()
srs_exec(args.debug, args.file, args.code, args.hex)
srs_exec(args.debug, args.file, args.code)

0 comments on commit 0cee3ca

Please sign in to comment.