Ad
  • Custom User Avatar

    Many modern compilers already perform automatic tail-recursion optimisations, and I suspect rustc does too.

    According to cargo-asm, the following is your function in assembly. Despite my very shallow knowledge in assembly, I believe it is tail-recursion optimised since there are only jumps and no calls.

    rust_test::zeros:
     je      .LBB0_1
     mov     r8, rcx
     xor     ecx, ecx
     movabs  r9, -3689348814741910323
    .LBB0_3:
     mov     rax, r8
     mul     r9
     shr     rdx, 2
     add     rcx, rdx
     cmp     r8, 4
     mov     r8, rdx
     ja      .LBB0_3
     mov     rax, rcx
     ret
    .LBB0_1:
     xor     ecx, ecx
     mov     rax, rcx
     ret
    
  • Custom User Avatar

    I'm very impressed by this solution, and it's author, but completely unimpressed by the people who voted the solution "best practice". While it is certainly clever, I wouldn't say a recursive solution is exactly "best practice". I was thought in A&D to avoid recursion wherever possible. Typically this sort of thing will crowd the stack with the return adresses and parameters of outer calls. It is very functional in style though. So kudos, once again, for cleverness.