点号参数
Coddy 面向 Kotlin 开发者的 R 课程的第 24 课,共 48 课。
Kotlin 的 vararg 会将末尾的值收集到一个数组中,而展开运算符会在调用时展开现有数组。R 的 dots 携带了额外的参数 promise,可以通过 list 捕获或进行转发。do.call 会将函数应用于参数列表。请定义空输入时的行为,而不是假设 dots 已经是一个数值向量。
Kotlin
fun sum(vararg values:Int)=values.sum()
fun main(){
val values=intArrayOf(2,4,6);println(sum(*values))
}
R
longest <- function(...) { words<-c(...); if(length(words))max(nchar(words)) else 0 }
cat(longest(), longest("tea","coffee"), sep="\n")在将其作为集合使用之前,请显式捕获 dots。
挑战
简单实现 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="")
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Kotlin 开发者的 R中的所有课
自己练习: R 在线编译器