re-implement fold in terms of head and tail recursion