rewrite caching to a closure function