Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Creating a memoised function via pipe #148

Closed
jeffkeller-einc opened this issue Jun 9, 2023 · 1 comment
Closed

Creating a memoised function via pipe #148

jeffkeller-einc opened this issue Jun 9, 2023 · 1 comment

Comments

@jeffkeller-einc
Copy link

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
Copy link
Member

wch commented Jun 9, 2023

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"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants