点号参数
Coddy 面向 Python 开发者的 R 语言 课程的第 24 课,共 48 课。
Python 的星号参数会将位置参数收集到一个元组中。R 的点号参数可以接受额外参数,这些参数可以被收集为列表,也可以转发给另一个函数。do.call 会使用参数列表调用函数。不要假设点号参数已经是一个普通的原子向量,并且要在简化之前定义空输入时的行为。
Python
def longest(*words):
return max((len(word) for word in words), default=0)
print(longest())
print(longest(*["tea", "coffee"]))R
longest <- function(...) { words<-c(...); if(length(words))max(nchar(words)) else 0 }
cat(longest(), longest("tea","coffee"), sep="\n")先有意地捕获点号参数,再将其视为集合。
挑战
简单实现 spread_width(...):所有参数都是单独的有限数值。返回最大值减去最小值;如果没有参数,则返回 0。适配器使用 do.call 展开输入序列。
保留已声明的公共 API。锁定的可见驱动程序会直接检查它,也会输出 solve(lines)。输入符合给定约定;所有运算结果都很小且有限。
你的代码写在 Functions.R 和 Exercise.R 中。main.R 会按顺序加载依赖项,并包含提供的输入/输出代码;不能编辑它。
亲手试试
source("Functions.R")
source("Exercise.R")
stopifnot(identical(spread_width(9,2,7),7),identical(spread_width(),0))
lines <- suppressWarnings(readLines(file("stdin"), warn=FALSE))
cat(solve(lines), "\n", sep="")
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Python 开发者的 R 语言中的所有课
自己练习: R 在线编译器