Python Vs Ruby ( again )

B

Brad Phelan

There was a discussion a while back in trying to get Ruby looking like
Python using an indentation scheme and I posted a possible solution to that

http://xtargets.com/snippets/posts/show/68

There is also the Lazibi library ( sorry no link .. google it ) that
does a similar thing.

I thought to be fair I'd have a hack in the opposite direction and see
if I could emulate Ruby's block notation in Python without
preprocessing. Turns out that you can get pretty close though if a bit
ugly due to the statement vs expression nature of the language.

Note that in python a return statement from within a function with a
yield statement is illegal some some ugly workaround is necessary.

A few short examples .....

from ruby import rubyfi

#Ruby's inject method
@rubyfi
def inject(ret, iter, a = 0):
for x in iter:
a = yield a, x
ret(a)

#Ruby's collect method
@rubyfi
def collect(ret, iter):
r = []
for x in iter:
x = yield x,
r.append(x)
ret(r)

# Do a sum over a range
for r, s, x in inject ( range (1,6), 1 ) :
r(s+x)
print r()

# Generate a list
for r, s, x in inject ( range (1,6), [] ) :
s.append(x*x)
r(s)
print r()

# Collect some items
for r, x in collect ( range (1,6) ) :
r(x+x)
print r()

The library and some details is at

http://xtargets.com/snippets/posts/show/74

Can this be developed a little further or a little cleaner?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,071
Latest member
MetabolicSolutionsKeto

Latest Threads

Top