Skip to content

Conversation

@jetjinser
Copy link
Collaborator

@jetjinser jetjinser commented Feb 12, 2026

needs #408.

[210_19] (srfi srfi-165)

https://srfi.schemers.org/srfi-165/srfi-165.html

任务相关的代码文件

  • goldfish/srfi/srfi-165.scm
  • tests/goldfish/srfi/srfi-165-test.scm

如何测试

xmake b goldfish
./bin/goldfish tests/goldfish/srfi/srfi-165-test.scm

2026/2/12 实现 SRFI-165 (The Environment Monad)

What

  1. 完整实现 SRFI-165 规范,提供环境单子(Environment Monad)支持:

    • 环境变量管理:make-computation-environment-variable, computation-environment-ref/update/update!
    • 计算构造:make-computation, computation-pure, computation-bind
    • 环境操作:computation-ask, computation-local, computation-environment-copy
    • 控制流:computation-each, computation-sequence, computation-forked, computation-bind/forked
    • 语法糖:computation-fn, computation-with, computation-with!
    • 类型定义:define-computation-type
  2. 使用向量(vector)+ 哈希表 + alist 实现双层环境(local/global)查找机制

  3. 通过 box 模式模拟可变性(暂时无 SRFI-111,手动模拟)

  4. 提供默认计算类型 make-computation-environmentcomputation-run

Why

SRFI-165 提供了一种纯函数式的方式来处理隐式参数传递和上下文依赖计算,解决了以下问题:

  • 避免显式传递上下文对象(如配置、状态、IO句柄)
  • 支持函数式更新(update)与副作用更新(update!)的灵活组合
  • 通过 forked 实现环境隔离,支持临时修改不影响外层上下文
  • 为格式化输出(如 SRFI-166/159)、状态管理等场景提供基础抽象

How

核心架构

  • 环境变量(<computation-environment-variable>):通过 define-record-type 定义,包含名称、默认值、不可变标志和唯一ID
  • 环境结构:向量 [global-ht local-alist predefined-cells...],其中 global 为哈希表(SRFI-125),local 为 alist
  • 查找优先级:local 层 > global 层 > 默认值;预定义变量(predefined)直接存储在向量固定位置

关键实现细节

  • make-computation 将过程包装为接收 compute continuation 的形式,支持延迟执行
  • computation-bind 实现 monadic bind,支持多值传递(通过 call-with-values
  • computation-forked 使用 computation-environment-copy 创建环境浅拷贝,确保分支隔离
  • define-computation-type 为宏,在展开时生成带预定义变量的构造函数和运行器
  • 使用 variable-comparator(SRFI-128)确保哈希表键的正确比较

依赖:SRFI-1(列表操作)、SRFI-128(比较器)、SRFI-125(哈希表)

@jetjinser
Copy link
Collaborator Author

注 测试失败是因为需要 #408 合并后的 hash-table-copy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant