Menu
CoddyTech

상태 기반 정책 조합

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

R의 클로저는 데이터를 함께 보유합니다. 다른 함수에서 반환된 함수는 자신을 둘러싼 환경을 유지하므로, 그곳에서 정의된 변수를 계속 읽을 수 있습니다. C에서는 정책 구조체에 데이터 포인터와 함수 포인터를 결합할 수 있습니다. 함수는 컨텍스트를 명시적으로 전달받습니다. 이를 통해 상속, 캡처된 환경 또는 내장 클래스 런타임 없이 동작을 모델링합니다.

R

make_policy <- function(factor) function(n) n * factor
policy <- make_policy(3)
print(policy(4))

C17

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
struct Policy {void *context;int (*apply)(void*,int);};
static int multiply(void *context,int n){return *(int*)context*n;}
int main(void) {
int factor=3;struct Policy p={&factor,multiply};printf("%d\n",p.apply(p.context,4));
return 0;
}

포팅 규칙

모든 콜백 호출이 이루어지는 동안 컨텍스트를 유지하세요.

challenge icon

챌린지

쉬움

Policy는 context와 apply(context,value)를 저장합니다. 제공된 콜백을 동일한 context와 함께 한 번 호출하여 price_with(policy,value)를 구현하세요. 입력은 factor와 value입니다. 드라이버는 offset 정책도 제공하고 호출 횟수를 확인하므로, 곱셈을 하드 코딩하는 것만으로는 충분하지 않습니다.

잠금 해제된 소스 파일과 헤더 파일을 수정하세요. 이를 직접 호출하는, 화면에 표시된 잠긴 main.c와 선언된 공개 API의 호환성을 유지하세요. 다른 main을 추가하지 마세요. 작업에서 범위를 명시적으로 확인하지 않는 한, 모든 숫자 작업 테스트 데이터는 오버플로가 발생하지 않을 만큼 작습니다. 지정된 출력만 출력하세요. 표시된 경우 드라이버가 입력 파싱과 출력을 담당합니다.

직접 해보기

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
static int multiply(void *context,int n){return *(int*)context*n;}
typedef struct {int offset,calls;} Counter;
static int shifted(void *context,int n){Counter *p=context;p->calls++;return n+p->offset;}
int main(void){int factor,value;if(scanf("%d%d",&factor,&value)!=2)return 1;Counter c={7,0};if(price_with((Policy){&c,shifted},3)!=10 || c.calls!=1)return 3;printf("%d\n",price_with((Policy){&factor,multiply},value));return 0;}
quiz icon실력 점검

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

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

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