Menu
CoddyTech

经过验证的构造函数

Coddy 面向 Luau 开发者的 R 课程的第 33 课,共 48 课。

Luau 工厂可以通过显式检查以及错误或失败结果来验证运行时输入;类型注解不会强制执行所有业务不变量。R S3 构造函数可以在返回带标签的值之前调用 stop。S3 类属性不会自动提供 S4 正式有效性验证。请有意识地验证构造边界。

Luau

local function score(n)if n<0 then return nil,"negative" end;return {points=n} end;local value=assert(score(3));print(value.points)

R

new_window <- function(side) { if(side<=0)stop("side");structure(list(side=side),class="window") }
area <- function(x) x$side*x$side
cat(area(new_window(4)),"\n",sep="")

返回构造好的 S3 对象之前,请先验证其表示形式。

challenge icon

挑战

简单

为一个有限数实现 new_stock(count)。负值时使用 stop 拒绝;否则返回类为 stock、成员 count 为数值的对象。适配函数在发生错误时返回 count 或 invalid。

保留已声明的公共 API。可见的锁定驱动程序会直接检查它,并打印 solve(lines)。输入符合给定的约定;所有算术运算的数值都很小且有限。

你的代码写在 Stock.R 和 Exercise.R 中。main.R 按顺序加载依赖项,并包含提供的输入和输出代码;不能编辑它。

亲手试试

source("Stock.R")
source("Exercise.R")
stopifnot(inherits(new_stock(8),"stock"),identical(new_stock(8)$count,8),inherits(tryCatch(new_stock(-1),error=identity),"error"))
lines <- suppressWarnings(readLines(file("stdin"), warn=FALSE))
cat(solve(lines), "\n", sep="")
quiz icon自我测试

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

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

自己练习: R 在线编译器