S3 泛型派发
Coddy 面向 Go 开发者的 R 语言 课程的第 30 课,共 48 课。
Go 接口值通过满足方法集的具体动态类型来分派方法。R S3 使用包含 UseMethod 的泛型函数以及命名为 generic.class 的方法。对象可以携带一个有序的类向量,并使用默认回退机制。如果没有泛型函数的操作,仅凭类标签本身不会调用匹配的方法。
Go
package main
import ("fmt"; "strings")
type Channel interface{Send(string)string}
type Email struct{}
func(Email) Send(s string)string{return "email:"+s}
type Sms struct{}
func(Sms) Send(s string)string{return "sms:"+s}
func main(){
channels:=[]Channel{Email{},Sms{}}; out:=[]string{}; for _,c:=range channels {out=append(out,c.Send("hi"))}; fmt.Println(strings.Join(out,"|"))
}
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。可见的锁定驱动代码会直接对其进行检查,并打印 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="")
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Go 开发者的 R 语言中的所有课
自己练习: R 在线编译器