S3 泛型分派
Coddy 面向 Swift 开发者的 R 课程的第 30 课,共 48 课。
Swift 协议定义要求,遵循协议的值提供实现,具体调用哪个实现取决于所选的抽象。R S3 使用名为 UseMethod 的泛型调用,以及名为 generic.class 的函数。对象可以带有有序的类向量,并在默认情况下使用后备实现。仅附加类标签不会创建协议遵循关系,也不会调用方法。
Swift
protocol Channel { func send(_ text: String) -> String }
struct Email: Channel { func send(_ text: String) -> String { "email:" + text } }
struct Sms: Channel { func send(_ text: String) -> String { "sms:" + text } }
let channels: [any Channel] = [Email(), Sms()]
print(channels.map { $0.send("hi") }.joined(separator: "|"))
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 分派;名称相似的函数不会调用自身。
挑战
简单将 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="")
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Swift 开发者的 R中的所有课
自己练习: R 在线编译器