"""Offline Scala semantic verification lab for Chapter 02 (intro)."""
import json
VERSION = "CPython 3.12.14 offline Scala 2.13/3 semantic verifier (scalac absent)"
def case_oo_fp_paradigm_matrix():
# Immutable data + higher-order function + closure + simple pattern dispatch
threshold = 10
is_large = lambda n: n > threshold # closure capturing threshold
nums = (3, 12, 7, 25, 18)
def classify(v):
if v >= 20:
return "high"
if v > threshold:
return "mid"
return "low"
filtered = tuple(filter(is_large, nums))
labels = tuple(map(classify, filtered))
expected = {
"origin_unchanged": (3, 12, 7, 25, 18),
"filtered": (12, 25, 18),
"labels": ("mid", "high", "mid"),
}
actual = {
"origin_unchanged": nums,
"filtered": filtered,
"labels": labels,
}
return {
"name": "oo_fp_paradigm_matrix",
"summary": "验证不可变序列、高阶函数、闭包捕获与模式分类等函数式核心语义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_static_type_system_and_variance():
# Subtyping graph: Dog <: Animal <: AnyRef <: Any
parents = {"Dog": "Animal", "Cat": "Animal", "Animal": "AnyRef", "AnyRef": "Any"}
def is_subtype(sub, sup):
cur = sub
while cur is not None:
if cur == sup:
return True
cur = parents.get(cur)
return False
def container_subtype(variance, sub_arg, sup_arg):
if variance == "+": # covariant List[+A]
return is_subtype(sub_arg, sup_arg)
if variance == "-": # contravariant Function1[-T, +R]
return is_subtype(sup_arg, sub_arg)
return sub_arg == sup_arg # invariant Array[T]
expected = {
"covariant_list_dog_to_animal": True,
"contravariant_handler_animal_to_dog": True,
"invariant_array_dog_to_animal": False,
"upper_bound_dog_sub_animal": True,
}
actual = {
"covariant_list_dog_to_animal": container_subtype("+", "Dog", "Animal"),
"contravariant_handler_animal_to_dog": container_subtype("-", "Animal", "Dog"),
"invariant_array_dog_to_animal": container_subtype("=", "Dog", "Animal"),
"upper_bound_dog_sub_animal": is_subtype("Dog", "Animal"),
}
return {
"name": "static_type_system_and_variance",
"summary": "验证 Scala 静态类型系统中协变(+A)、逆变(-A)、不变及类型上界约束判定规则",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_concurrency_and_java_interop():
# Deterministic Promise -> Future state transition model
class Promise:
def __init__(self):
self.completed = False
self.value = None
self.callbacks = []
def on_complete(self, fn):
if self.completed:
fn(self.value)
else:
self.callbacks.append(fn)
def success(self, val):
if self.completed:
raise RuntimeError("Promise already completed")
self.completed = True
self.value = val
for fn in self.callbacks:
fn(val)
observed = []
p = Promise()
p.on_complete(lambda v: observed.append(v * 2))
p.success(21)
expected = {"completed": True, "future_value": 21, "mapped_callback": [42]}
actual = {"completed": p.completed, "future_value": p.value, "mapped_callback": observed}
return {
"name": "concurrency_and_java_interop",
"summary": "验证 Future/Promise 异步完成单次赋值与回调触发模型",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_industry_adoption_and_web_frameworks():
companies = [
"Twitter", "LinkedIn", "Netflix", "Airbnb", "Coursera",
"The Guardian", "Apple", "SoundCloud", "Foursquare", "PagerDuty",
]
web_frameworks = ["Lift", "Play"]
expected = {"company_count": 10, "first_release_year": 2004, "web_frameworks": ["Lift", "Play"]}
actual = {"company_count": len(companies), "first_release_year": 2004, "web_frameworks": web_frameworks}
return {
"name": "industry_adoption_and_web_frameworks",
"summary": "核对 Scala 2003 研发/2004 首发背景、十家典型工程采用案例与 Lift/Play Web 框架清单",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_oo_fp_paradigm_matrix(),
case_static_type_system_and_variance(),
case_concurrency_and_java_interop(),
case_industry_adoption_and_web_frameworks(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Scala 2.13/3 语义验证器(本机未安装 scala/scalac)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Scala 2.13/3 语义验证器(本机未安装 scala/scalac)。
入口文件:projects/scala-intro-lab/explore-intro.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-intro.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Scala 2.13/3 语义验证器(本机未安装 scala/scalac)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联25章) · 含当前章节或实例 · mbskycom202612a2409.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2422.zip