reduce condition nesting

Adam D. Ruppe destructionator at gmail.com
Sat Nov 25 22:05:42 UTC 2017


On Saturday, 25 November 2017 at 21:42:29 UTC, Ali Çehreli wrote:
> I tried to implement the following but gave up because I could 
> not ensure short circuit behaviour.
>
>     when(
>         c1.then(foo()),
>         c2.then(bar()),
>         otherwise(zar())
>     );
>
> Possible?

Bones: "Perhaps the professor can use your computer."

https://dlang.org/spec/function.html#lazy_variadic_functions

Dr. Nichols: "Lazy variadic functions?!"
Scotty: "That's the ticket, laddie."

---
import std.stdio;

void when(bool delegate()[] foo...) {
	foreach(i; foo) {
		if(i())
			return;
	}
}

bool then(bool c, lazy void what) {
	if(c) what();
	return c;
}

bool otherwise(lazy void what) {
	what;
	return true;
}


void foo() {
	writeln("foo evaled");
}
void bar() {
	writeln("bar evaled");
}
void zar() {
	writeln("zar evaled");
}

void main() {
	bool c1 = false;
	bool c2 = false;

     when(
         c1.then(foo()),
         c2.then(bar()),
         otherwise(zar())
     );
}
---


More information about the Digitalmars-d-learn mailing list