Microblog: A very long article Wikipedia article on the orientation of toilet paper [Jun 7th, 22:52] [R]

Saturday, March 21st, 2009

No for, no if

Categories: [ IT ]

The mission: write a program that iterates over a list and asks the user, on every item, if he wants to change the current number, or quit (and keep the rest of the list unchanged).

Here's a possible python implementation.

def loop(data, index):
  return decide(index == len(data) - 1, 
                lambda: quit(data), 
                lambda: run(data, index+1)
def decide(condition, iftrue, iffalse):
  return (iffalse, iftrue)[condition]()
def choose(selector, choices, default):
  return choices.get(selector, default)()
def change(data, index, new_value):
  data[index] = new_value
  return loop(data, index)
def run(data, index):
  print data[index]," Change? [n/q/]",
  reply = raw_input()
  return choose(reply.lower(),
                  "n": lambda: loop(data, index),
                  "q": lambda: quit(data)
                lambda: decide(reply.isdigit(),
                               lambda: change(data, index, int(reply)),
                               lambda: run(data, index)
def quit(data):
  return data
data = range(10)
print run(data, 0)

[ Posted on March 21st, 2009 at 18:09 | 2 comments | ]