S3 継承順序
Coddyの「GDScript開発者のためのR」コースのレッスン 39/48。
GDScript の extends と super は、クラスの継承と親クラスの動作への明示的な委譲を提供します。一方、R の S3 ディスパッチはクラス名の順序付きベクトルに従い、NextMethod はそのチェーンを続行します。拡張するメソッドが次の結果を置き換えたり誤って繰り返したりせず、1 回だけ組み合わせることを確認しましょう。
GDScript
extends SceneTree
class Base:
var price = 5
func total(quantity):
return price * quantity
class Delivery extends Base:
var fee = 2
func total(quantity):
return super.total(quantity) + fee
func _init():
var delivery = Delivery.new()
print(str(delivery.total(3)) + ":" + str(delivery.total(0)))
quit()R
sound <- function(x)UseMethod("sound")
sound.soft <- function(x)paste0(NextMethod(),"?")
sound.bell <- function(x)"ring"
x<-structure(list(),class=c("soft","bell"))
cat(sound(x),"\n",sep="")S3 のクラスの順序はディスパッチチェーンに影響します。
チャレンジ
簡単ジェネリック関数 fee(x) を定義してください。parcel メソッドは x$units*2 を返します。urgent メソッドは NextMethod()+5 を返します。入力フラグが 1 の場合、アダプターはクラス c("urgent","parcel") を作成し、それ以外の場合はクラス parcel を作成します。入力は、0 または 1 のフラグに続く、0 以上の単位数です。
宣言された公開 API はそのままにしてください。表示されているロック済みドライバーは、solve(lines) を出力するだけでなく、API を直接検証します。入力は指定された契約を満たしており、すべての計算は小さく有限です。
コードは Parcel.R と Exercise.R に記述してください。main.R は依存関係を順番に読み込み、用意された入出力コードを含んでいます。編集することはできません。
自分で試してみよう
source("Parcel.R")
source("Exercise.R")
stopifnot(identical(fee(structure(list(units=7),class=c("urgent","parcel"))),19),identical(fee(structure(list(units=7),class="parcel")),14))
lines <- suppressWarnings(readLines(file("stdin"), warn=FALSE))
cat(solve(lines), "\n", sep="")
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
GDScript開発者のためのRのすべてのレッスン
自分で練習してみよう: Rオンラインコンパイラ