Name: Anonymous 2007-02-17 10:03
I've been turning Python's statements into expressions and such. Think of it like a mini-mini-Lisp built on top of Python. I'll post some code for shits and laughs. This post will have the "plambda" module, and the next three posts will be alternative implementations of a simple function using a simple algorithm to return primes in a list within a given range.
Of course, the function versions are 10 and 9.3 times slower than the native version, and their syntax is insane due to explicit lambdas, but it was fun to try.
This is plambda.py:
Of course, the function versions are 10 and 9.3 times slower than the native version, and their syntax is insane due to explicit lambdas, but it was fun to try.
This is plambda.py:
class Break (Exception):
pass
class Continue (Exception):
pass
def lazy(v):
if callable(v):
return v()
else:
return v
def Pass(*a):
pass
def Do(*fns):
ret = None
for fn in fns:
ret = lazy(fn)
return ret
def If(condfn, ltrue, lfalse=None):
if condfn():
return lazy(ltrue)
else:
return lazy(lfalse)
def Unless(condfn, ltrue, lfalse=None):
if not condfn():
return lazy(ltrue)
else:
return lazy(lfalse)
def While(condfn, *fns):
ret = None
while condfn():
try:
ret = Do(*fns)
except Continue:
pass
except Break:
break
return ret
def Until(condfn, *fns):
ret = None
while not condfn():
try:
ret = Do(*fns)
except Continue:
pass
except Break:
break
return ret
def DoWhile(*fns): #last fns is condfn
condfn = fns[-1]
fns = fns[:-1]
while True:
try:
ret = Do(*fns)
except Continue:
pass
except Break:
break
if not condfn():
break
return ret
def DoUntil(*fns): #last fns is condfn
condfn = fns[-1]
fns = fns[:-1]
while True:
try:
ret = Do(*fns)
except Continue:
pass
except Break:
break
if condfn():
break
return ret
def For(literable, *fns):
ret = None
for i in lazy(literable):
try:
for fn in fns:
if callable(fn):
ret = fn(i)
else:
ret = fn
except Continue:
pass
except Break:
break
return ret
def Try(*fns): #Last arg = dict of Except(exception): fn(e)
dexcept = fns[-1]
fns = fns[:-1]
try:
return Do(*fns)
except Exception, e:
if e.__class__ in dexcept:
return dexcept[e.__class__](e)
else:
raise
def Except(exception):
return exception.__class__
def TryThese(*fns):
ret = None
for fn in fns:
try:
ret = lazy(fn)
except:
continue
break
return ret
def Raise(e):
raise e