added tailrec annotation for tail-call optimization