S3 继承顺序
Coddy 面向 Ruby 开发者的 R 课程的第 39 课,共 48 课。
Ruby 的继承、包含的模块和 super 都会参与其祖先查找链。R 的 S3 则使用有序的类名向量,而 NextMethod 会继续沿着该分派链查找。测试一下,扩展方法是否恰好将下一个结果组合一次,而不是假设 Ruby 的祖先顺序。
Ruby
class BasePass;def cost;12;end;end;class DiscountPass < BasePass;def cost;super-5;end;end;puts DiscountPass.new.cost
R
sound <- function(x)UseMethod("sound")
sound.soft <- function(x)paste0(NextMethod(),"?")
sound.bell <- function(x)"ring"
x<-structure(list(),class=c("soft","bell"))
cat(sound(x),"\n",sep="")S3 的类顺序会影响分派链。
挑战
简单定义通用函数 fee(x)。它的 parcel 方法返回 x$units*2。它的 urgent 方法返回 NextMethod()+5。当输入标志为 1 时,适配器会创建类 c("urgent","parcel"),否则类为 parcel。输入是非负的单位数,后跟标志 0 或 1。
保留已声明的公共 API。可见的锁定驱动程序会直接检查它,并打印 solve(lines)。输入符合所述约定,所有运算结果都很小且有限。
你的代码写在 Parcel.R 和 Exercise.R 中。main.R 会按顺序导入依赖项,并包含提供的输入/输出代码,不能编辑。
亲手试试
source("Parcel.R")
source("Exercise.R")
stopifnot(identical(fee(structure(list(units=7),class=c("urgent","parcel"))),19),identical(fee(structure(list(units=7),class="parcel")),14))
lines <- suppressWarnings(readLines(file("stdin"), warn=FALSE))
cat(solve(lines), "\n", sep="")
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Ruby 开发者的 R中的所有课
自己练习: R 在线编译器