Menu
CoddyTech

S3 继承顺序

Coddy 面向 C 开发者的 R 语言课程 课程的第 39 课,共 48 课。

C 可以嵌入一个基记录,并显式委托给辅助函数,但没有内置的类继承或 next 方法链。R 的 S3 使用有序的类名向量,而 NextMethod 会沿着该链继续分派。请明确测试增强行为,确保方法是在下一个结果的基础上添加内容,而不是意外替换或重复自身。

C

#include <stdio.h>
struct Base { int price; };
struct Child { struct Base base; int fee; };
static int base_total(const struct Base *self, int quantity)
{
    return self->price * quantity;
}
static int child_total(const struct Child *self, int quantity)
{
    return base_total(&self->base, quantity) + self->fee;
}
int main(void)
{
    struct Child child = {{3}, 2};
    printf("%d\n", child_total(&child, 4));
    return 0;
}

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 类的顺序会影响分派链。

challenge icon

挑战

简单

定义泛型函数 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="")
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C 开发者的 R 语言课程中的所有课

自己练习: R 在线编译器