DCSIMG
If we didn't have loops - Doron's .NET Space

If we didn't have loops

I've stumbled upon this article which explains how to implement delegates in Java. The issue of implementing things we have taken for granted  reminded me of a course I took a few years ago, in a language called Scheme, which is a variant of Lisp. Scheme is a functional language, and has a very recursive nature. It has no loops. As exercises at this course, we had to implement things such as While and For loops and add them to the Scheme interpreter.

This made me think of how I would implement loops if didn't have them at C#. I figured I would want to have something like this:

[Test] public void TestWhile() { int i = 0; Loops.Do(delegate() { i++; }).While(delegate() { return i < 5; }); Assert.AreEqual(5, i); }

And this is how I coded it up. LoopOptions does most of the work. Its While method accepts a condition (which is the same as the built-in Predicate<T> only it's not generic. Same goes for Action). It uses tail recursion to repeat the action. And that's it.

public delegate bool Condition(); public delegate void Action(); public class LoopOptions { private Action _action; public LoopOptions(Action action) { _action = action; } public void While(Condition cond) { if (!cond()) return; _action(); While(cond); } } public class Loops { public static LoopOptions Do(Action act) { return new LoopOptions(act); } }

Now it will be super-easy to implement a repeat-until pattern, we'll just add this method to LoopOptions:

public void Until(Condition cond) { _action(); While( delegate() { return !cond(); } ); }

And call it like this:

Loops.Do(delegate() { i++; }).Until(delegate() { return i == 5; });

Of course this has absolutely no practical usage, but I somehow find this disturbingly fun.

Now for the reader's challenge: implement the for loop...

Published Tuesday, February 27, 2007 6:49 PM by dorony
תגים:,

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: