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

Add purrr_continue() #1100

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

Conversation

mgirlich
Copy link
Contributor

@mgirlich mgirlich commented Sep 5, 2023

Closes #1099.

The idea is to easily continue a call to map() and keep intermediate results.

devtools::load_all("~/GitHub/purrr/")
#> ℹ Loading purrr

slow_function <- function(x) {
  if (x == 5) {
    stop("something went wrong")
  }
  
  x - 1
}

slow_function2 <- function(x) {
  print(x)
  x
}

to_process <- 1:10
map(1:10, slow_function)
#> [1] 0
#> Error in `map()`:
#> ℹ In index: 5.
#> Caused by error in `.f()`:
#> ! something went wrong
#> Backtrace:
#>      ▆
#>   1. ├─purrr::map(1:10, slow_function)
#>   2. │ └─purrr:::map_("list", .x, .f, ..., .progress = .progress) at purrr/R/map.R:129:2
#>   3. │   ├─purrr:::with_indexed_errors(...) at purrr/R/map.R:182:2
#>   4. │   │ └─base::withCallingHandlers(...) at purrr/R/map.R:234:2
#>   5. │   ├─purrr:::call_with_cleanup(...)
#>   6. │   └─global .f(.x[[i]], ...)
#>   7. │     └─base::stop("something went wrong")
#>   8. └─base::.handleSimpleError(...)
#>   9.   └─purrr (local) h(simpleError(msg, call))
#>  10.     └─cli::cli_abort(...) at purrr/R/map.R:248:8
#>  11.       └─rlang::abort(...)
all <- purrr_continue(.f = slow_function2)
#> [1] 5
#> [1] 6
#> [1] 7
#> [1] 8
#> [1] 9
#> [1] 10
all
#> [[1]]
#> [1] 0
#> 
#> [[2]]
#> [1] 1
#> 
#> [[3]]
#> [1] 2
#> 
#> [[4]]
#> [1] 3
#> 
#> [[5]]
#> [1] 5
#> 
#> [[6]]
#> [1] 6
#> 
#> [[7]]
#> [1] 7
#> 
#> [[8]]
#> [1] 8
#> 
#> [[9]]
#> [1] 9
#> 
#> [[10]]
#> [1] 10

# for some reason this now starts at 5 :-(
run2 <- map(1:10, slow_function)
#> [1] 5

Created on 2023-09-05 with reprex v2.0.2

i <- 0L
print(i)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For some reason I don't understand in the second run i is 5 at this point even though we just assigned 0 to it...

)
}

purrr_continue <- function(.f = NULL) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be even nicer if updating the original .f would work, i.e.

map(x, f)
# something went wrong

# update `f`
f <- function(x) ...
# no need to pass the new `f` to `purrr_continue()`
purrr_continue()

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

Successfully merging this pull request may close these issues.

Allow to continue interrupted map()
1 participant