Menu
CoddyTech

S3 泛型分派

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

GDScript 会在脚本对象上调用方法,并且不同的类可以使用共同的方法契约。R S3 使用泛型调用 UseMethod,以及名为 generic.class 的函数。对象可以携带有序的类向量和默认回退。仅有类标签并不会在没有泛型操作的情况下调用名称相似的方法。

GDScript

extends SceneTree
class Email:
    func send(message):
        return "email:" + message
class Sms:
    func send(message):
        return "sms:" + message
func _init():
    var results = PackedStringArray()
    for sender in [Email.new(), Sms.new()]:
        results.append(sender.send("ready"))
    print("|".join(results))
    quit()

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。可见的锁定驱动程序会直接检查它,并打印 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自我测试

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

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

自己练习: R 在线编译器