Tail recursive optimization of average