简体   繁体   中英

Can tail recursion apply to this code?

I have a simple piece of code, that addresses this (poorly stated, out of place) question :

template<typename It>
bool isAlpha(It first, It last)
{
    return (first != last && *first != '\0') ? 
        (isalpha(static_cast<int>(*first)) && isAlpha(++first, last)) : true;
}

I'm trying to figure out how can I go about implementing it in a tail recursive fashion , and although there are great sources like this answer , I can't wrap my mind around it.

Can anyone help ?

EDIT

I'm placing the disassembly code below; The compiler is gcc 4.9.0 compiling with -std=c++11 -O2 -Wall -pedantic the assembly output is

bool isAlpha<char const*>(char const*, char const*):
    cmpq    %rdi, %rsi
    je  .L5
    movzbl  (%rdi), %edx
    movl    $1, %eax
    testb   %dl, %dl
    je  .L12
    pushq   %rbp
    pushq   %rbx
    leaq    1(%rdi), %rbx
    movq    %rsi, %rbp
    subq    $8, %rsp
.L3:
    movsbl  %dl, %edi
    call    isalpha
    testl   %eax, %eax
    jne .L14
    xorl    %eax, %eax
.L2:
    addq    $8, %rsp
    popq    %rbx
    popq    %rbp
.L12:
    rep ret
.L14:
    cmpq    %rbp, %rbx
    je  .L7
    addq    $1, %rbx
    movzbl  -1(%rbx), %edx
    testb   %dl, %dl
    jne .L3
.L7:
    movl    $1, %eax
    jmp .L2
.L5:
    movl    $1, %eax
    ret

To clarify cdhowie's point, the function can be rewritten as follows (unless I made a mistake):

bool isAlpha(It first, It last)
{
  if (first == last)
    return true;
  if (*first == '\0')
    return true;
  if (!isalpha(static_cast<int>(*first))
    return false;
  return isAlpha(++first, last);
}

Which would indeed allow for trivial tail call elimination.

This is normally a job for the compiler, though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM