将库存系统移植到 Swift
Coddy Swift 开发者的 Lua 课程的第 47 课,共 48 课。
挑战
中等将参考 Swift 程序移植为 Lua 模块。每行输入都包含一个小写 ASCII 名称、一个冒号和一个带符号的整数增量。按名称汇总,只保留最终总计为正数的名称,按名称升序排序,并返回用逗号连接的 name=total 条目。如果没有符合条件的名称,则返回 empty。在 inventory.lua 中实现 inventory.aggregate(lines);由 app 负责格式化结果。所有输入行格式正确。
Swift 参考代码
var counts: [String: Int] = [:]
while let line = readLine() {
let pieces = line.split(separator: ":", maxSplits: 1)
let name = String(pieces[0])
counts[name, default: 0] += Int(pieces[1])!
}
let rows = counts.keys.sorted().filter { counts[$0]! > 0 }
.map { "\($0)=\(counts[$0]!)" }
print(rows.isEmpty ? "empty" : rows.joined(separator: ","))
编辑 app.lua、inventory.lua。可见的锁定文件 main.lua 会从标准输入读取内容,生成由多行组成的序列,调用 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))
Swift 开发者的 Lua中的所有课
自己练习: Lua 在线编译器