memoizing pattern rec functions