Consider: bool b1search(int[] a, int x) { if (!a.length) return 0; auto mid = a.length / 2; auto e = a[mid]; return x == e ? true : x < e ? b1search(a[0 .. mid], x) : b1search(a[mid + 1 .. $], x); } bool b2search(int[] a, int x) { if (!a.length) return 0; auto mid = a.length / 2; auto e = a[mid]; if (x == e) return true; return x < e ? b2search(a[0 .. mid], x) : b2search(a[mid + 1 .. $], x); } bool b3search(int[] a, int x) { if (!a.length) return 0; auto mid = a.length / 2; auto e = a[mid]; if (x == e) return true; if (x < e) return b3search(a[0 .. mid], x); return b3search(a[mid + 1 .. $], x); } bool b4search(int[] a, int x) { if (!a.length) return 0; auto mid = a.length / 2; auto e = a[mid]; if (x == e) return true; return b4search(x < e ? a[0 .. mid] : a[mid + 1 .. $], x); } void main() { } After compiling with: dmd -O -release test and looking at the generated object file, only b3search and b4search are tail-call optimized, but not b1search and b2search. Tail-call optimization doesn't seem to work when a ternary expression is used with return.
https://github.com/D-Programming-Language/dmd/pull/745
Created attachment 1257 [details] Partial solution I took a stab at this one. I've gotten b2search to compile to the same assembly code as b3search. I did not handle nested ternary operators following a return statement.
Created attachment 1258 [details] Partial solution
@WalterBright created dlang/dmd pull request #11725 "fix Issue 3713 - Tail call optimization not enabled with the ?: operator" fixing this issue: - fix Issue 3713 - Tail call optimization not enabled with the ?: operator https://github.com/dlang/dmd/pull/11725
dlang/dmd pull request #11725 "fix Issue 3713 - Tail call optimization not enabled with the ?: operator" was merged into master: - fc88c8befa53870256fbe8f2abbba3c397469323 by Walter Bright: fix Issue 3713 - Tail call optimization not enabled with the ?: operator https://github.com/dlang/dmd/pull/11725