蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线校验 Scala 模式匹配优先级、类型模式、样例类解构与模式守卫

PYTHONWindows x64、CPython 3.12.14 离线 Scala 2.13/3 语义验证器(本机未安装 scala/scalac)。explore-pattern-matching.py
explore-pattern-matching.py142 行
"""Offline Scala semantic verification lab for Chapter 21 (pattern-matching)."""
import json
from dataclasses import dataclass, replace

VERSION = "CPython 3.12.14 offline Scala 2.13/3 semantic verifier (scalac absent)"


def case_int_match_first_hit_order():
    def match_test(x):
        match x:
            case 1:
                return "one"
            case 2:
                return "two"
            case _:
                return "many"

    expected = {"m1": "one", "m2": "two", "m3": "many"}
    actual = {"m1": match_test(1), "m2": match_test(2), "m3": match_test(3)}
    return {
        "name": "int_match_first_hit_order",
        "summary": "验证整型 match 表达式自上而下顺序尝试、命中即止且无隐式穿透语义",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_any_type_pattern_and_wildcard():
    def match_any(x):
        if x == 1 and type(x) is int:
            return "one"
        if x == "two":
            return 2
        if type(x) is int:
            return "scala.Int"
        return "many"

    expected = {
        "two_str": 2,
        "test_str": "many",
        "int_1": "one",
        "int_6": "scala.Int",
    }
    actual = {
        "two_str": match_any("two"),
        "test_str": match_any("test"),
        "int_1": match_any(1),
        "int_6": match_any(6),
    }
    return {
        "name": "any_type_pattern_and_wildcard",
        "summary": "验证值模式、字符串常量模式、类型模式(y: Int)与通配符(_)的多类型匹配优先级",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_case_class_unapply_destructuring():
    @dataclass(frozen=True)
    class Person:
        name: str
        age: int

    people = [Person("Alice", 25), Person("Bob", 32), Person("Charlie", 32)]
    results = []
    for p in people:
        match p:
            case Person("Alice", 25):
                results.append("Hi Alice!")
            case Person("Bob", 32):
                results.append("Hi Bob!")
            case Person(name, age):
                results.append(f"Age: {age} year, name: {name}?")

    expected = {
        "greetings": ["Hi Alice!", "Hi Bob!", "Age: 32 year, name: Charlie?"],
    }
    actual = {"greetings": results}
    return {
        "name": "case_class_unapply_destructuring",
        "summary": "验证样例类 Person 在 match 中按构造参数精确匹配与变量绑定解构",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_case_class_auto_members_and_guards():
    @dataclass(frozen=True)
    class Person:
        name: str
        age: int

    a1 = Person("Alice", 25)
    a2 = Person("Alice", 25)
    older = replace(a1, age=26)

    def classify_guard(p):
        match p:
            case Person(name, age) if age >= 30:
                return f"senior:{name}"
            case Person(name, _):
                return f"junior:{name}"

    expected = {
        "structural_equals": True,
        "same_hash": True,
        "copy_age": 26,
        "guard_alice": "junior:Alice",
        "guard_bob": "senior:Bob",
    }
    actual = {
        "structural_equals": a1 == a2,
        "same_hash": hash(a1) == hash(a2),
        "copy_age": older.age,
        "guard_alice": classify_guard(a1),
        "guard_bob": classify_guard(Person("Bob", 32)),
    }
    return {
        "name": "case_class_auto_members_and_guards",
        "summary": "验证样例类自动生成的不可变 val 字段、结构相等 equals/hashCode、copy 以及模式守卫(if)",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_int_match_first_hit_order(),
        case_any_type_pattern_and_wildcard(),
        case_case_class_unapply_destructuring(),
        case_case_class_auto_members_and_guards(),
    ]
    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-pattern-matching-lab/explore-pattern-matching.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-pattern-matching.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Scala 2.13/3 语义验证器(本机未安装 scala/scalac)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Scala

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2427.zip

下载课程关联工程包:Scala

课程关联工程包(登记关联25章) · 含当前章节或实例 · mbskycom202612a2409.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习