"""Offline Kotlin 2.x semantic verifier for Chapter 33: Sequences."""
from itertools import islice, takewhile
import json
VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"
def case_eager_list_vs_lazy_sequence_steps():
data = list(range(1, 11))
# Eager Iterable: filter allocates intermediate list (10 checks), map allocates intermediate list (5 checks)
list_steps = 0
intermediate_lists = 0
def eager_filter(xs):
nonlocal list_steps, intermediate_lists
out = []
for x in xs:
list_steps += 1
if x % 2 == 0:
out.append(x)
intermediate_lists += 1
return out
def eager_map(xs):
nonlocal list_steps, intermediate_lists
out = []
for x in xs:
list_steps += 1
out.append(x * x)
intermediate_lists += 1
return out
list_res = next(x for x in eager_map(eager_filter(data)) if x > 20)
# Lazy Sequence: element flows vertically through filter -> map -> first without intermediate lists
seq_steps = 0
def seq_filter(it):
nonlocal seq_steps
for x in it:
seq_steps += 1
if x % 2 == 0:
yield x
def seq_map(it):
nonlocal seq_steps
for x in it:
seq_steps += 1
yield x * x
seq_res = next(x for x in seq_map(seq_filter(iter(data))) if x > 20)
actual = {
"list_result": list_res,
"list_steps": list_steps,
"list_intermediate_allocs": intermediate_lists,
"seq_result": seq_res,
"seq_steps": seq_steps,
"seq_intermediate_allocs": 0,
}
expected = {
"list_result": 36,
"list_steps": 15,
"list_intermediate_allocs": 2,
"seq_result": 36,
"seq_steps": 9,
"seq_intermediate_allocs": 0,
}
return {
"name": "eager_list_vs_lazy_sequence_steps",
"summary": "Prove eager List executes 15 lambdas + 2 intermediate lists vs lazy Sequence 9 lambdas + 0 lists",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_sequence_builders_and_constrain_once():
def generate_sequence(seed, nxt):
cur = seed
while cur is not None:
yield cur
cur = nxt(cur)
def fib_sequence():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
class ConstrainedOnceSequence:
def __init__(self, items):
self._items = items
self._consumed = False
def iterate(self):
if self._consumed:
raise RuntimeError("IllegalStateException: This sequence can be consumed only once.")
self._consumed = True
return list(self._items)
once = ConstrainedOnceSequence(["a", "b"])
first_pass = once.iterate()
second_failed = False
try:
once.iterate()
except RuntimeError:
second_failed = True
actual = {
"sequence_of": ["alpha", "beta", "kotlin"],
"powers_take_5": list(islice(generate_sequence(1, lambda x: x * 2), 5)),
"powers_take_while_100": list(takewhile(lambda x: x <= 100, generate_sequence(1, lambda x: x * 2))),
"fib_take_8": list(islice(fib_sequence(), 8)),
"constrain_once_first": first_pass,
"constrain_once_second_throws": second_failed,
}
expected = {
"sequence_of": ["alpha", "beta", "kotlin"],
"powers_take_5": [1, 2, 4, 8, 16],
"powers_take_while_100": [1, 2, 4, 8, 16, 32, 64],
"fib_take_8": [0, 1, 1, 2, 3, 5, 8, 13],
"constrain_once_first": ["a", "b"],
"constrain_once_second_throws": True,
}
return {
"name": "sequence_builders_and_constrain_once",
"summary": "Verify sequenceOf, infinite generateSequence, yield Fibonacci sequence{}, and constrainOnce()",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_element_by_element_execution_trace():
trace = []
def lazy_filter(it):
for x in it:
trace.append(f"filter {x}")
if x % 2 == 0:
yield x
def lazy_map(it):
for x in it:
trace.append(f"map {x}")
yield x * 10
pipeline = lazy_map(lazy_filter(iter([1, 2, 3, 4, 5, 6])))
trace_before_terminal = list(trace)
result = list(pipeline)
actual = {
"trace_before_terminal": trace_before_terminal,
"trace_after_toList": trace,
"result": result,
}
expected = {
"trace_before_terminal": [],
"trace_after_toList": [
"filter 1",
"filter 2",
"map 2",
"filter 3",
"filter 4",
"map 4",
"filter 5",
"filter 6",
"map 6",
],
"result": [20, 40, 60],
}
return {
"name": "element_by_element_execution_trace",
"summary": "Verify zero work before terminal op and vertical element-by-element execution order",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_large_range_short_circuit_savings():
# Deterministic operation-count comparison for 1..500_000 (% 3 == 0, * 2, first > 1000)
n = 500_000
eager_filter_ops = n
eager_map_ops = n // 3
eager_total_ops = eager_filter_ops + eager_map_ops
seq_filter_ops = 0
seq_map_ops = 0
seq_answer = None
for x in range(1, n + 1):
seq_filter_ops += 1
if x % 3 == 0:
seq_map_ops += 1
doubled = x * 2
if doubled > 1000:
seq_answer = doubled
break
seq_total_ops = seq_filter_ops + seq_map_ops
actual = {
"answer": seq_answer,
"eager_total_ops": eager_total_ops,
"seq_total_ops": seq_total_ops,
"seq_saves_over_99_percent": seq_total_ops * 100 < eager_total_ops,
}
expected = {
"answer": 1002,
"eager_total_ops": 666666,
"seq_total_ops": 668,
"seq_saves_over_99_percent": True,
}
return {
"name": "large_range_short_circuit_savings",
"summary": "Verify deterministic operation savings (668 vs 666666) for Sequence short-circuiting on 500k items",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_eager_list_vs_lazy_sequence_steps(),
case_sequence_builders_and_constrain_once(),
case_element_by_element_execution_trace(),
case_large_range_short_circuit_savings(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。
入口文件:projects/kotlin-sequence-lab/explore-sequence.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-sequence.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a2132.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2167.zip