I'm playing around with pushing Python (2.7, via the pythonista iOS interpreter) to do some weird functional things. Specifically, I'm trying to implement a one-line fizzbuzz using nested if-else lambdas and map. But I'm new to this kind of dirty trick, and it isn't going so well.
Take the following code:
alist = [1, 2, 3, 15, 5]
claw = map(lambda x: 'Fizzbuzz' if x % 15 == 0 else lambda x: 'Fizz' if x % 3 == 0 else lambda x: 'Buzz' if x % 5 == 0 else x, alist)
print "claw"
print claw
print
claw2 = map(lambda x: 'scratch' if x == 1 else 2, alist)
print "claw2"
print claw2
This code produces the following output:
claw
[<function <lambda> at 0x3f19fb4>, <function <lambda> at 0x36ba534>, <function <lambda> at 0x3ffa3e4>, 'Fizzbuzz', <function <lambda> at 0x3ffaa74>]
claw2
['scratch', 2, 2, 2, 2]
After searching around, it seems likely that the problem in claw is that the list elements aren't passed through to the inner lambdas (per this SO: Scope of python lambda functions and their parameters ). Ok, so then I tried nesting the maps in too:
claw3 = map(lambda x: 'Fizzbuzz' if x % 15 == 0 else map(lambda x: 'Fizz' if x % 3 == 0 else map(lambda x: 'Buzz' if x % 5 == 0 else x, alist), alist), alist)
print "claw3"
print claw3
That at least produced values, but obviously not quite what I was trying to achieve:
claw3
[[[1, 2, 3, 'Buzz', 'Buzz'], [1, 2, 3, 'Buzz', 'Buzz'], 'Fizz', 'Fizz', [1, 2, 3, 'Buzz', 'Buzz']], [[1, 2, 3, 'Buzz', 'Buzz'], [1, 2, 3, 'Buzz', 'Buzz'], 'Fizz', 'Fizz', [1, 2, 3, 'Buzz', 'Buzz']], [[1, 2, 3, 'Buzz', 'Buzz'], [1, 2, 3, 'Buzz', 'Buzz'], 'Fizz', 'Fizz', [1, 2, 3, 'Buzz', 'Buzz']], 'Fizzbuzz', [[1, 2, 3, 'Buzz', 'Buzz'], [1, 2, 3, 'Buzz', 'Buzz'], 'Fizz', 'Fizz', [1, 2, 3, 'Buzz', 'Buzz']]]
And now my brain has run out. Obviously, the repeated calls to map are evaluating the whole list over and over, but if there's no way to get the variables to the nested lambdas without it, am I stuck? I suppose there might be some solution involving mutating the list, like deleting the list item every time a lambda returns a value, but that seems unreasonably complex as well as totally un-functional. I am so close to a one-line functional fizzbuzz! Does anyone have any clues here?
EDIT: Thanks, y'all. For your collective amusement/reward, some fully-implemented one-line fizzbuzzes: