"""Offline Dart 3.x semantic verification lab for Chapter 13 (generics)."""
import json
VERSION = "CPython 3.12.14 offline Dart 3.x semantic verifier (dart SDK absent)"
def case_generic_classes_and_type_inference():
class Box:
def __init__(self, type_arg: type, value):
if not isinstance(value, type_arg):
raise TypeError(f"Expected {type_arg.__name__}, got {type(value).__name__}")
self.type_arg = type_arg
self._value = value
def get_value(self):
return self._value
def set_value(self, new_val):
if not isinstance(new_val, self.type_arg):
raise TypeError(f"Expected {self.type_arg.__name__}, got {type(new_val).__name__}")
self._value = new_val
class Pair:
def __init__(self, key, value):
self.key = key
self.value = value
def __str__(self) -> str:
return f"Pair({self.key}: {self.value})"
int_box = Box(int, 42)
auto_box = Box(type("自动推断为 String"), "自动推断为 String")
wrong_rejected = False
try:
int_box.set_value("hello")
except TypeError:
wrong_rejected = True
p1 = Pair("bluesky", 10)
p2 = Pair("score", 95.5)
expected = {
"int_box_val": 42,
"auto_inferred_type": "str",
"wrong_type_rejected": True,
"pairs": ["Pair(bluesky: 10)", "Pair(score: 95.5)"],
}
actual = {
"int_box_val": int_box.get_value(),
"auto_inferred_type": auto_box.type_arg.__name__,
"wrong_type_rejected": wrong_rejected,
"pairs": [str(p1), str(p2)],
}
return {
"name": "generic_classes_and_type_inference",
"summary": "校验泛型类 Box<T> 与 Pair<K, V> 的具体化类型约束、构造实参推断与跨类型拦截",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_generic_functions_and_swap():
def first_element(items: list):
if not items:
raise ValueError("ArgumentError: 列表不能为空")
return items[0]
def swap(items: list, i: int, j: int):
items[i], items[j] = items[j], items[i]
names = ["bluesky", "Dart", "Flutter"]
scores = [95, 88, 72]
letters = ["A", "B", "C"]
swap(letters, 0, 2)
empty_caught = False
try:
first_element([])
except ValueError:
empty_caught = True
expected = {
"first_name": "bluesky",
"first_score": 95,
"swapped": ["C", "B", "A"],
"empty_throws": True,
}
actual = {
"first_name": first_element(names),
"first_score": first_element(scores),
"swapped": letters,
"empty_throws": empty_caught,
}
return {
"name": "generic_functions_and_swap",
"summary": "校验泛型函数 firstElement<T>(含空表异常)与原地交换函数 swap<T>",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_bounded_type_extends_num():
class Calculator:
def __init__(self, type_arg: type, a, b):
if not issubclass(type_arg, (int, float)) or type_arg is bool:
raise TypeError("Type argument violates 'T extends num'")
self.a = a
self.b = b
def ops(self) -> dict:
return {
"add": float(self.a + self.b),
"sub": float(self.a - self.b),
"mul": float(self.a * self.b),
"div": f"{self.a / self.b:.2f}",
}
int_ops = Calculator(int, 10, 3).ops()
dbl_ops = Calculator(float, 3.5, 1.5).ops()
str_rejected = False
try:
Calculator(str, "a", "b")
except TypeError:
str_rejected = True
expected = {
"int_ops": {"add": 13.0, "sub": 7.0, "mul": 30.0, "div": "3.33"},
"double_ops": {"add": 5.0, "sub": 2.0, "mul": 5.25, "div": "2.33"},
"string_violates_num_bound": True,
}
actual = {
"int_ops": int_ops,
"double_ops": dbl_ops,
"string_violates_num_bound": str_rejected,
}
return {
"name": "bounded_type_extends_num",
"summary": "校验 T extends num 类型边界支持 int/double 运算并拒绝 String 等非数值类型",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_generic_collections_and_repository():
class Repository:
def __init__(self, elem_type: type):
self._elem_type = elem_type
self._items = []
def add(self, item):
if not isinstance(item, self._elem_type):
raise TypeError("Repository element type mismatch")
self._items.append(item)
def find_by_id(self, item_id: str):
for it in self._items:
if it["id"] == item_id:
return it
return None
def get_all(self) -> tuple:
# Simulates List.unmodifiable
return tuple(self._items)
numbers = [1, 2, 3, 4, 5, 6]
evens = [n for n in numbers if n % 2 == 0]
labels = [f"ITEM-{n}" for n in numbers]
folded_sum = sum(numbers, 0)
user_repo = Repository(dict)
user_repo.add({"id": "u1", "name": "bluesky"})
user_repo.add({"id": "u2", "name": "Alice"})
product_repo = Repository(dict)
product_repo.add({"id": "p1", "name": "Dart 教程", "price": 29.99})
product_repo.add({"id": "p2", "name": "Flutter 教程", "price": 49.99})
expected = {
"evens": [2, 4, 6],
"label_count": 6,
"folded_sum": 21,
"found_u1": "bluesky",
"found_p2": "Flutter 教程",
"missing_u9": None,
"unmodifiable_view_len": 2,
}
actual = {
"evens": evens,
"label_count": len(labels),
"folded_sum": folded_sum,
"found_u1": user_repo.find_by_id("u1")["name"],
"found_p2": product_repo.find_by_id("p2")["name"],
"missing_u9": user_repo.find_by_id("u9"),
"unmodifiable_view_len": len(user_repo.get_all()),
}
return {
"name": "generic_collections_and_repository",
"summary": "校验泛型集合过滤映射折叠及 Repository<T> 泛型仓库模式与不可变列表返回",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_generic_classes_and_type_inference(),
case_generic_functions_and_swap(),
case_bounded_type_extends_num(),
case_generic_collections_and_repository(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Dart 3.x 语义验证器(本机未安装原生 Dart SDK)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Dart 3.x 语义验证器(本机未安装原生 Dart SDK)。
入口文件:projects/dart-generics-lab/explore-generics.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-generics.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Dart 3.x 语义验证器(本机未安装原生 Dart SDK)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2543.zip
课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a2534.zip