最終課題:センサーのポリシー
Coddyの「Ruby開発者のためのRust」コースのレッスン 48/48。
チャレンジ
中級Rubyの参照実装を移植し、ダックタイピングによる受け入れポリシーを明示的なRustトレイトに置き換えてください。Rubyのnilまたは整数という解析結果はResult値に置き換え、Rubyの整数には参照パーサーと同じ明示的なi32の範囲チェックが必要です。入力は最初にしきい値を表すi32整数があり、その後に空白で区切られた読み取り値トークンが最大100個続きます。各トークンは最大31 ASCIIバイトです。有効な読み取り値は、先頭に符号があってもなくてもよく、10進数字で構成され、i32の範囲内に収まります。また、実行中の合計値はすべてi32の範囲内に収まります。reading::parse(text: &str) -> Result<i32, &'static str>は、前後に空白のないトークン全体を受け取り、それ以外の場合はErr("invalid")を返します。Accept::accept(&self, value: i32) -> boolがポリシーの契約です。Above::new(limit: i32) -> Aboveは、指定値より厳密に大きい値を受け入れます。Report::new() -> Reportは空の状態で開始します。feed<R: Accept + ?Sized>(&mut self, value: i32, rule: &R)は受け入れられた読み取り値を件数と合計値に加算し、拒否された読み取り値の場合は状態を維持します。count(&self) -> usizeとtotal(&self) -> i32は状態を参照するメソッドです。トレイトオブジェクトを含め、呼び出し側が定義したAcceptポリシーはすべて動作しなければなりません。入力の処理にはAboveを使い、count total invalidを出力してください。読み取り値がなければ0 0 0を出力します。
必要な公開APIを実装し、exercise::solve(input: &str) -> Stringから結果を返してください。末尾に改行を付けてはいけません。編集可能なコード内で出力してはいけません。編集できないドライバーは必要なAPIを個別に検査し、標準入力をすべて読み取り、返されたテキストを末尾に改行を1つ付けて出力します。
コードはexercise.rs、rule.rs、above.rs、report.rs、reading.rsに記述してください。main.rsには指定された入出力コードがあり、編集できません。
同じ有効な入力仕様に対するRubyの参照実装全体:
def parse_reading(text)
return nil unless text.match?(/\A[+-]?[0-9]+\z/)
value = Integer(text, 10)
(-2147483648..2147483647).cover?(value) ? value : nil
end
class Above
def initialize(limit)
@limit = limit
end
def accept(value)
value > @limit
end
end
class Report
attr_reader :count, :total
def initialize
@count = 0
@total = 0
end
def feed(value, rule)
return unless rule.accept(value)
@count += 1
@total += value
end
end
words = STDIN.read.split
rule = Above.new(Integer(words.shift, 10))
report = Report.new
invalid = 0
words.each do |word|
value = parse_reading(word)
if value.nil?
invalid += 1
else
report.feed(value, rule)
end
end
puts "#{report.count} #{report.total} #{invalid}"
自分で試してみよう
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod rule;
mod above;
mod report;
mod reading;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// 公開APIの検証開始
use rule::Accept;
let p=above::Above::new(-3); assert!(p.accept(-2)); assert!(!p.accept(-3)); assert!(!p.accept(-4));
assert_eq!(reading::parse("+17"), Ok(17)); assert_eq!(reading::parse("-0"), Ok(0));
for s in &["", "+", " 3", "2x", "2147483648"] { assert_eq!(reading::parse(s), Err("invalid")); }
struct Odd;
impl rule::Accept for Odd { fn accept(&self, value: i32) -> bool { value % 2 != 0 } }
let policy: &dyn rule::Accept=&Odd;
let mut r=report::Report::new(); assert_eq!(r.count(),0); assert_eq!(r.total(),0);
r.feed(-7,policy); r.feed(4,policy); r.feed(9,policy);
assert_eq!(r.count(),2); assert_eq!(r.total(),2);
r.feed(0,policy); assert_eq!(r.count(),2); assert_eq!(r.total(),2);
r.feed(1,&p); assert_eq!(r.count(),3); assert_eq!(r.total(),3);
assert_eq!(report::Report::new().count(),0);
// 公開APIの検証終了
println!("{}", exercise::solve(&input));
}
Ruby開発者のためのRustのすべてのレッスン
自分で練習してみよう: Rustオンラインコンパイラ