Menu
CoddyTech

S3 泛型分派

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

C# 接口和虚方法会根据声明类型和实现类进行分派。R S3 使用通用调用 UseMethod 和命名为 generic.class 的方法。对象可以带有有序的类向量,并使用默认回退。仅有类标签并不会在没有通用操作的情况下执行匹配的方法。

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
IChannel[] channels={new Email(),new Sms()}; Console.WriteLine(string.Join("|",channels.Select(c=>c.Send("hi"))));
interface IChannel {string Send(string text);}
class Email:IChannel {public string Send(string text)=>"email:"+text;}
class Sms:IChannel {public string Send(string text)=>"sms:"+text;}

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自我测试

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

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

自己练习: R 在线编译器