S3 继承顺序
Coddy 面向 Rust 开发者的 R 课程的第 39 课,共 48 课。
Rust 使用组合和 trait,而不是通过超类方法链实现类继承。R S3 对象带有一个有序的类名向量,NextMethod 会继续沿着它们的分派链调用。测试增强如何组合下一个结果,而不是把 trait 默认实现或组合辅助函数转换成假定的类层次结构。
Rust
struct Base;
impl Base{fn value(&self)->i32{3}}
struct Child{base:Base}
impl Child{fn value(&self)->i32{self.base.value()}}
fn main() {
let child=Child{base:Base}; println!("{}",child.value());
}
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="")
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Rust 开发者的 R中的所有课
自己练习: R 在线编译器