传递函数
本课属于 Coddy R 学习旅程的“逻辑与流程”单元。第 28 课,共 64 课。
函数可以将另一个函数作为参数,并调用它。下面的 apply_twice() 适用于任何单参数函数:
apply_twice <- function(f, x) f(f(x))
print(apply_twice(\(x) x + 3, 10))
print(apply_twice(toupper, "ok"))输出:
[1] 16
[1] "OK"内置函数(例如 sum、max 或 toupper)也是值,所以传递它们时只写名称,不加括号。加上括号后,它们就会被调用:
summarize <- function(xs, how) how(xs)
print(summarize(c(4, 9, 2), max))
print(summarize(c(4, 9, 2), sum))输出:
[1] 9
[1] 15接收谓词的函数(谓词是返回 TRUE 或 FALSE 的函数),可以按照任意规则统计或筛选值:
count_if <- function(xs, keep) {
n <- 0
for (x in xs) if (keep(x)) n <- n + 1
n
}
print(count_if(c(3, 8, 10, 5), \(x) x %% 2 == 0))
print(count_if(c(3, 8, 10, 5), \(x) x > 4))输出:
[1] 2
[1] 3调用者决定行为,而函数提供循环,因此一个函数可以处理许多情况:
transform_each <- function(xs, f) {
out <- c()
for (x in xs) out <- c(out, f(x))
out
}
print(transform_each(1:4, \(x) x * 10))
print(transform_each(c("a", "b"), toupper))输出:
[1] 10 20 30 40
[1] "A" "B"挑战
简单完成 apply_n(f, x, n)。对 x 调用 f,然后对结果调用 f,总共调用 n 次,并返回最终值。当 n 为 0 时,原样返回 x。
提供的代码定义了三个函数:double、inc 和 half。它会读取其中一个函数的名称、起始值和 n,并打印 apply_n() 的结果。
亲手试试
apply_n <- function(f, x, n) {
# 在这里编写你的代码
x
}
# 提供的输入和输出代码:保持原样
input <- suppressWarnings(readLines(file("stdin")))
ops <- list(double = \(x) x * 2, inc = \(x) x + 1, half = \(x) x / 2)
cat(apply_n(ops[[input[1]]], as.numeric(input[2]), as.numeric(input[3])), sep = "\n")
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
逻辑与流程中的所有课
自己练习: R 在线编译器