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)
The original question was: Can you provide a set of primitives for a reasonable language/framework that allows you to write an equivalent of the following program:
without a break or any other terminating condition within the loop?
Naturally the solution contains in it's specification something that includes conditionals with repetitive structures. This is ok, if the primitives aren't directly equivalent to if/switch/break or other loop breaking tools and the program written with them is doesn't contain those either.
Here is my thought about one such possible primitive set: zipT(a,b)- take two streams, a and b. Resulting stream will pair elements of a and b, returning elements from a until they run out and then produces the remaining elements from b. (easier to code than explain)
take(n,a) - make a stream that produces first n elements from a
index(x,a) - return number containing the position of x in stream a
mapcurry(op,s) - given operation op, return a stream of operations op(s1),op(s2)..
ask(q) - Ask replacement for value q & return it.
and the program, where originals is the stream of original values that are being replaced:
(execution order must of course be by-need.)