Menu
CoddyTech

インベントリを移植する

Coddyの「Rust開発者のためのLuau」コースのレッスン 47/48。

challenge icon

チャレンジ

中級

参照用のRustプログラムをLuauモジュールに移植してください。各入力行は、小文字のASCII名、コロン、符号付き整数の差分で構成されます。名前ごとに集計し、最終合計が正のものだけを残し、名前を昇順に並べて、name=totalの項目をカンマで結合して返します。残る項目がない場合はemptyを返します。inventory.luauでinventory.aggregate(lines)を実装し、結果の書式設定はappで行います。すべての入力行は正しい形式です。

Rustの参照実装

use std::collections::BTreeMap;
use std::io::{self, Read};
fn aggregate(input: &str) -> BTreeMap<String, i64> {
    let mut counts = BTreeMap::new();
    for line in input.lines() {
        let (name, delta) = line.split_once(':').unwrap();
        *counts.entry(name.to_owned()).or_insert(0) += delta.parse::<i64>().unwrap();
    }
    counts
}
fn main() {
    let mut input = String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    let rows: Vec<_> = aggregate(&input).into_iter()
        .filter(|(_, total)| *total > 0)
        .map(|(name, total)| format!("{}={}", name, total)).collect();
    println!("{}", if rows.is_empty() { "empty".to_owned() } else { rows.join(",") });
}

app.luauとinventory.luauを編集してください。表示されているロック済みのmain.luauは、標準入力を行の並びに読み込み、app.run(lines)を呼び出して、返された値を最後に改行を1つ付けて出力します。診断メッセージを出力したり、モジュール名を変更したりしないでください。入力が空の場合、空の並びになります。すべての数値入力はオーバーフローしない程度に小さい値です。

公開APIの確認項目:inventory.aggregate(lines)は、符号付き差分を合計した新しいテーブルを返し、合計がゼロの項目も保持します。入力が空の場合は空のテーブルになります。書式設定と絞り込みはappで行います。ロック済みのドライバーはapp.runを呼び出す前にこの動作を確認します。これらの確認に成功した場合、何も出力されません。

自分で試してみよう

-- 公開 API のチェック
do
local inventory=require("./inventory")
local counts=inventory.aggregate({"pen:3","pen:-1","book:0"})
assert(counts.pen==2 and counts.book==0,"aggregate must sum signed deltas by name")
local empty=inventory.aggregate({})
assert(next(empty)==nil,"aggregate empty input returns an empty table")
assert(counts.pen==2,"aggregation calls retain independent result state")
end
local app = require("./app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))

Rust開発者のためのLuauのすべてのレッスン

自分で練習してみよう: Luauオンラインコンパイラ