Menu
CoddyTech

S3 泛型分派

Coddy 面向 Ruby 开发者的 R 课程的第 30 课,共 48 课。

Ruby 会向接收者发送方法,并沿着祖先查找链进行查找,模块也会参与这条查找链。R S3 则使用包含 UseMethod 的泛型,以及命名为 generic.class 的函数。对象带有一个有序的类向量,并可选择使用默认回退。仅有类标签并不会调用方法,还需要执行泛型操作。

Ruby

class BracketRenderer;def render(text);"["+text+"]";end;end;def show(renderer,text);renderer.render(text);end;puts show(BracketRenderer.new,"hi")

R

speak <- function(x) UseMethod("speak")
speak.bell <- function(x) "ring"
speak.default <- function(x) "quiet"
cat(speak(structure(list(),class="bell")), "\n", sep="")

UseMethod 执行 S3 分派;名称相似的函数不会调用自身。

challenge icon

挑战

简单

将 describe(x) 定义为 S3 泛型函数,describe.default(x) 返回 plain,describe.parcel(x) 根据 x$units 返回 parcel:N。输入是一个非负数,适配器会构造一个 parcel 类列表。

保留已声明的公共 API。可见的锁定驱动程序会直接检查该 API,并打印 solve(lines)。输入符合所述约定,所有算术运算的数值都很小且有限。

将代码写入 Parcel.R 和 Exercise.R。main.R 会按顺序加载依赖项,并包含提供的输入和输出代码,不能编辑。

亲手试试

source("Parcel.R")
source("Exercise.R")
stopifnot(identical(describe(9),"plain"),identical(describe(structure(list(units=7),class="parcel")),"parcel:7"))
lines <- suppressWarnings(readLines(file("stdin"), warn=FALSE))
cat(solve(lines), "\n", sep="")
quiz icon自我测试

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

面向 Ruby 开发者的 R中的所有课

自己练习: R 在线编译器