S4 有效性契约
Coddy 面向 C 开发者的 R 语言课程 课程的第 40 课,共 48 课。
C 声明会确定存储类型,但不会强制执行任意业务不变量;必须编写验证代码。R S4 将形式化类、槽和方法签名与有效性函数结合起来,后者会返回 TRUE 或诊断字符串。构造对象时会检查有效性。将 setValidity 包在 invisible 中,以避免打印其返回的对象。
C
#include <stdio.h>
struct Score{int points;};
static int score_new(int points,struct Score *out){if(points<0)return 0;out->points=points;return 1;}
int main(void) {
struct Score score; if(score_new(3,&score))printf("%d\n",score.points);
return 0;
}
R
setClass("LabelDemo",slots=c(text="character"))
invisible(setValidity("LabelDemo",function(object)if(length(object@text)==1&&nzchar(object@text))TRUE else "text required"))
cat(validObject(new("LabelDemo",text="tea")),"\n",sep="")S4 有效性规则不会自动验证任意普通列表。
挑战
简单定义 S4 类 Capacity,并设置数值型槽位 value。它的有效性函数只接受一个有限的非负值,否则返回消息 invalid capacity。使用 new 实现 make_capacity(n)。适配器返回槽位值;如果构造时发生错误,则返回 invalid。
保留声明的公共 API。可见的锁定驱动程序会直接检查它,并打印 solve(lines)。输入符合所述约定;所有算术运算的数值都很小且有限。
你的代码分别写入 Capacity.R 和 Exercise.R。main.R 会按顺序加载依赖项,并包含提供的输入/输出代码;不能编辑它。
亲手试试
source("Capacity.R")
source("Exercise.R")
stopifnot(is(make_capacity(8),"Capacity"),identical(make_capacity(8)@value,8),inherits(tryCatch(make_capacity(-2),error=identity),"error"))
lines <- suppressWarnings(readLines(file("stdin"), warn=FALSE))
cat(solve(lines), "\n", sep="")
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C 开发者的 R 语言课程中的所有课
自己练习: R 在线编译器