10_Functional_Programming Flashcards

(4 cards)

1
Q

Front

A

Back

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you iterate with purrr::map() variants?

A

map() returns list; map_dbl/map_int/map_chr enforce types.

Code:
library(purrr)
map_dbl(1:5, ~ .x^2)
map2_chr(letters[1:3], 1:3, ~ paste0(.x, .y))
pmap_dbl(list(a=1:3, b=4:6), ~ ..1 + ..2)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you handle missing or failing iterations in purrr?

A

Use possibly() and safely() wrappers.

Code:
library(purrr)
safe_log <- safely(log, otherwise = NA_real_)
map_dbl(c(1, -1, 10), ~ safe_log(.x)$result)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you reduce/accumulate values with purrr?

A

Use reduce() and accumulate().

Code:
library(purrr)
reduce(1:5, +) # 15
accumulate(1:5, +) # 1 3 6 10 15

How well did you know this?
1
Not at all
2
3
4
5
Perfectly