Why function template 'among' is of complexity O(1) and not O(n)?

anonymous anonymous at example.com
Thu Feb 20 13:23:08 PST 2014


On Thursday, 20 February 2014 at 17:08:11 UTC, Jakob Ovrum wrote:
> On Thursday, 20 February 2014 at 13:40:38 UTC, anonymous wrote:
>> When the value is not needed at compile time, the optimizer 
>> may go for it, but that's not guaranteed.
>
> That's not really true. The optimizer will never try CTFE 
> because of the halting problem. Runtime is runtime, 
> compile-time is compile-time - they are clearly separated by 
> the context of the expression alone.

LDC does it. The halting problem just dictates that it can't be
done in all cases.

test.d:
---
int among(Value, Values...) (Value value, Values values)
{
      foreach (i, v; values) if (value == v) return i + 1;
      return 0;
}
int main()
{
      return among(3, 1,2,5,3);
}
---

`ldmd2 -O -c test.d && objdump -d -M intel test.o` (excerpt):
---
0000000000000000 <_Dmain>:
     0:   b8 04 00 00 00          mov    eax,0x4
     5:   c3                      ret
     6:   66 2e 0f 1f 84 00 00    nop    WORD PTR 
cs:[rax+rax*1+0x0]
     d:   00 00 00
---

I.e. int main() {return 4;}


More information about the Digitalmars-d-learn mailing list