Microblogi: A very long article Wikipedia article on the orientation of toilet paper [7. kes klo 22:52] [V]

Lauantai, 21. maaliskuuta 2009

No for, no if

Käännös: [ Google ]

Kategoriat: [ ATK ]

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)

[ Postattu 21. maaliskuuta 2009 klo 18.09 | 2 kommenttia | ]