Menu
CoddyTech

함수 협업

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

C에서는 함수 포인터와 컨텍스트를 함께 사용해 동작을 주입할 수 있으며, 이때 가리키는 상태는 호출이 끝날 때까지 유지되어야 합니다. R 함수는 일급 값이며 클로저나 리스트에 보관됩니다. 팩터리가 전달된 함수 인수를 즉시 평가해야 할 때 force가 유용합니다. 기본값으로 조용히 대체하지 말고 제공된 협력 객체를 호출하세요.

C

#include <stdio.h>
struct Policy {
    int factor;
    int (*apply)(const struct Policy *self, int quantity);
};
struct Order { const struct Policy *policy; };
static int multiply(const struct Policy *self, int quantity)
{
    return self->factor * quantity;
}
static int order_total(const struct Order *self, int quantity)
{
    return self->policy->apply(self->policy, quantity);
}
int main(void)
{
    struct Policy policy = {2, multiply};
    struct Order order = {&policy};
    printf("%d\n", order_total(&order, 3));
    return 0;
}

R

new_page <- function(title){force(title);function()paste0("<",title(),">")}
page<-new_page(function()"hello")
cat(page(),"\n",sep="")

평가 시점이 캡처 계약의 일부라면 팩터리 인수를 강제로 평가하세요.

challenge icon

챌린지

쉬움

new_formatter(prefix,transform)를 구현해 transform(text)를 호출한 다음 prefix를 앞에 붙이는 함수를 반환하세요. 입력은 접두사와 소문자 단어 하나이며, 어댑터가 toupper를 주입합니다. 독립적인 테스트에서는 서로 다른 함수를 주입하며, 이를 존중해야 합니다.

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

코드는 Formatter.R와 Exercise.R에 작성하세요. main.R은 종속 항목을 순서대로 불러오고 제공된 입력/출력 코드를 포함하므로 수정할 수 없습니다.

직접 해보기

source("Formatter.R")
source("Exercise.R")
f<-new_formatter("!",function(x)paste0(x,x));stopifnot(identical(f("ab"),"!abab"))
lines <- suppressWarnings(readLines(file("stdin"), warn=FALSE))
cat(solve(lines), "\n", sep="")
quiz icon실력 점검

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

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

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