Functional Programming ใน R
Map
${a, b, c, d} => fn => {fn(a), fn(b), fn(c), fn(d)}$
# Create some random data
set.seed(1234567890)
l <- replicate(20, runif(sample(1:10, 1)), simplify = FALSE)
# With Map
Map(length,l) |> unlist()
#> [1] 8 7 10 7 9 5 2 5 5 6 9 1 9 3 5 3 3 4 5 10
# with sapply
sapply(l, length)
#> [1] 8 7 10 7 9 5 2 5 5 6 9 1 9 3 5 3 3 4 5 10
Reduce
\[\{a, b, c, d\} =\> fn =\> fn(fn(fn(fn(x, a), b), c), d)\]
# calculate 10!
Reduce(`*`,1:10)
#> [1] 3628800
# calculate x raised to the power of n
xPwy <- function(x,y) Reduce(`*`,rep(x,y))
xPwy(3,7)
#> [1] 2187
# create a number from digits
Reduce(\(x, y) 10*x + y, c(4,5,1,6,7,8), init = 0 )
#> [1] 451678
Reduce
\[x =\> $fn$ =\> $fn(fn(fn(fn(x))))\]
# find the root of f(x) = log(x)-exp(-x)
fn <- function(x){
log(x)-exp(-x)
}
gn <- function(x){
exp(exp(-x))
}
root <- Reduce(\(x, f) f(x), rep(list(gn), 20), init = 1)
root
#> [1] 1.3098
fn(root)
#> [1] -3.433383e-10