移植库存系统
Coddy 面向 Rust 开发者的 Luau 课程的第 47 课,共 48 课。
挑战
中等将参考 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 会将 stdin 读入一个行序列,调用 app.run(lines),并输出其返回值,末尾加一个换行符。不要输出诊断信息,也不要更改模块名称。空输入会生成空序列。所有数值输入都足够小,不会溢出。
公共 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 在线编译器