r-lib / memoise

Easy memoisation for R
https://memoise.r-lib.org
Other
317 stars 59 forks source link

Creating a memoised function via pipe #148

Closed jeffkeller-einc closed 1 year ago

jeffkeller-einc commented 1 year ago

Anonymous functions can be memoised like so:

myfun <- memoise::memoise(function(x) {x + 1})
class(myfun)
[1] "memoised" "function"

However, it would be convenient to be able to use a pipe (native or magrittr) to do this. Like the above example, it would avoid creating an intermediate object but it would also make the code more readable (especially if the function spans many lines).

But this doesn't seem to work:

myfun <- function(x) {x + 1} |> memoise::memoise()
class(myfun)
# [1] "function"
wch commented 1 year ago

I think the problem in your example is due to how R parses the code. Notice that the body of myfun actually contains the |> operator:

myfun <- function(x) {x + 1} |> memoise::memoise()
myfun
#> function(x) {x + 1} |> memoise::memoise()

This is equivalent to:

function(x) memoise::memoise({ x + 1})

So you need to add parentheses around the function definition:

myfun <- (function(x) {x + 1}) |> memoise::memoise()
myfun
#> Memoised Function:
#> function(x) {x + 1}
class(myfun)
#> [1] "memoised" "function"