Menu
CoddyTech

S3 상속 순서

Coddy의 C 개발자를 위한 R 코스 레슨. 48개 중 39번째.

C는 기본 레코드를 포함하고 헬퍼에 명시적으로 위임할 수 있지만, 내장된 클래스 상속이나 다음 메서드 체인은 없습니다. R S3는 정렬된 클래스 이름 벡터를 사용하며, NextMethod는 해당 체인을 따라 디스패치를 계속합니다. 메서드가 다음 결과에 더하도록 동작을 명시적으로 테스트하여, 실수로 결과를 대체하거나 자기 자신을 반복하지 않도록 하세요.

C

#include <stdio.h>
struct Base { int price; };
struct Child { struct Base base; int fee; };
static int base_total(const struct Base *self, int quantity)
{
    return self->price * quantity;
}
static int child_total(const struct Child *self, int quantity)
{
    return base_total(&self->base, quantity) + self->fee;
}
int main(void)
{
    struct Child child = {{3}, 2};
    printf("%d\n", child_total(&child, 4));
    return 0;
}

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 클래스 순서는 디스패치 체인에 영향을 줍니다.

challenge icon

챌린지

쉬움

일반 fee(x)를 정의하세요. parcel 메서드는 x$units*2를 반환합니다. urgent 메서드는 NextMethod()+5를 반환합니다. 어댑터는 입력 플래그가 1이면 클래스 c("urgent","parcel")를 만들고, 그렇지 않으면 클래스 parcel을 만듭니다. 입력은 0 이상의 단위 수 다음에 플래그 0 또는 1이 오는 형식입니다.

선언된 공개 API를 유지하세요. 보이는 잠금 드라이버는 solve(lines)를 출력할 뿐 아니라 이를 직접 확인합니다. 입력은 명시된 조건을 충족하며 모든 산술 연산은 작은 유한 값입니다.

코드는 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="")
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

C 개발자를 위한 R의 모든 레슨

직접 연습해 보세요: 온라인 R 컴파일러