校验构造函数
Coddy 面向 Go 开发者的 R 语言 课程的第 33 课,共 48 课。
Go 构造函数可以在检查不变量后返回一个值和一个错误;使用 New 前缀是一种约定。R S3 构造函数可以在返回带标签的值之前调用 stop。S3 类属性不提供 S4 风格的有效性规则。在构造时校验输入,而不是指望方法去修复格式错误的状态。
Go
package main
import ("fmt")
type Score struct{Points int}
func NewScore(points int)(Score,error){if points<0{return Score{},fmt.Errorf("negative")};return Score{Points:points},nil}
func main(){
score,err:=NewScore(3);if err!=nil{panic(err)};fmt.Println(score.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 对象之前校验其表示。
挑战
简单为一个有限数字实现 new_stock(count)。使用 stop 拒绝负值;否则返回包含数值型成员 count 的 stock 类。适配器返回 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="")
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Go 开发者的 R 语言中的所有课
自己练习: R 在线编译器