Skip to content

Incorrect caching of recursive functions #158

@venpopov

Description

@venpopov

If you memoise a recursive function, like the factorial function below, and then call the function in a loop or sapply, you get duplicate cache keys. For example, here we get 19 keys in the cache instead of 10:

library(memoise)

cache_size <- function(fun) {
  env <- environment(fun)
  cache <- env[["_cache"]]
  cache$size()
}

factorial <- function(n) {
  if (n == 1) return(1)
  n * factorial(n-1)
}

factorial <- memoise(factorial)

cache_size(factorial)
#> [1] 0

for (i in 1:10) {
  a <- factorial(i)
}

cache_size(factorial)
#> [1] 19

Created on 2026-02-13 with reprex v2.1.1

Created on 2026-02-13 with reprex v2.1.1

If instead you call the function manually with all the arguments, you get the correct number:

library(memoise)

cache_size <- function(fun) {
  env <- environment(fun)
  cache <- env[["_cache"]]
  cache$size()
}

factorial <- function(n) {
  if (n == 1) return(1)
  n * factorial(n-1)
}

factorial <- memoise(factorial)

cache_size(factorial)
#> [1] 0

a <- factorial(1)
a <- factorial(2)
a <- factorial(3)
a <- factorial(4)
a <- factorial(5)
a <- factorial(6)
a <- factorial(7)
a <- factorial(8)
a <- factorial(9)
a <- factorial(10)

cache_size(factorial)
#> [1] 10

Created on 2026-02-13 with reprex v2.1.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions