PythonでRubyっぽいmap
思いつきでやった。
>>> Array([1, 2, 3, 4, 5])
[1, 2, 3, 4, 5]
>>> _.map("""|x|
if x % 2 == 0:
return x / 2
else:
return x * 3 + 1""")
[4, 1, 10, 2, 16]
種明かしは下記
>>> class Array(list):
def map(self, code):
import re
m = re.match("\|(.*?)\|(.*)", code, re.DOTALL)
d = {}
exec("def foo(%s):\n%s" % m.groups(), d)
return map(d["foo"], self)