Menu
CoddyTech

복습: 선택 가능한 정책

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

challenge icon

챌린지

쉬움

입력은 [amount,double]입니다. Rule은 evaluate(int):int를 정의합니다. KeepRule은 입력값을 반환하고, DoubleRule은 두 배로 만듭니다. Evaluator(Rule)의 run(int):int는 위임 방식으로 실행되며, 타사 규칙도 받을 수 있습니다. 드라이버는 불리언값에 따라 선택합니다.

제공된 main 스크립트는 표준 입력에서 JSON 값 하나를 읽고, 명시된 공개 API를 확인한 다음 결과를 출력합니다. 출력하지 않도록 모듈 선언을 구현하세요. 실행 파일을 대체하거나 모듈에서 입력을 읽지 마세요. 입력은 명시된 유형 및 범위를 만족합니다.

Rule.php, KeepRule.php, DoubleRule.php, Evaluator.php를 수정하세요. main.php는 잠긴 진입 파일입니다. 종속성은 상대 파일 이름과 함께 require_once __DIR__를 사용합니다.

직접 해보기

<?php
declare(strict_types=1);
require_once __DIR__."/Rule.php";
require_once __DIR__."/KeepRule.php";
require_once __DIR__."/DoubleRule.php";
require_once __DIR__."/Evaluator.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}

$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
$r=new class implements Rule {public function evaluate(int $n):int{return $n+5;}};ensure((new Evaluator($r))->run(4)===9 && (new KeepRule())->evaluate(3)===3 && (new DoubleRule())->evaluate(3)===6,"all policies");
echo (string)(new Evaluator($input[1]?new DoubleRule():new KeepRule()))->run($input[0]),"\n";

Rust 개발자를 위한 PHP의 모든 레슨

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