write-functional
Write code in functional style — pure core, effects at edges, composition over mutation.
- License 许可
- Apache-2.0
- 所属仓库
- usurobor/cnos
- 最近更新
- 2026-11-07
- Stars
- ★ 9
- Forks
- 0
01 前言 Front Matter
- name
- write-functional
- scope
- task-local
- triggers
- [ "functional", "pure", "immutable", "composition", "algebraic" ]
- description
- Write code in functional style — pure core, effects at edges, composition over mutation.
- governing_question
- How do we write code with a pure core, effects at the edges, and composition replacing mutation?
02 资源文件 24
- 资产文件assets/directory-browser.css2.9 KB
- 资产文件assets/favicon.ico15.0 KB
- 资产文件assets/novel-theme.css612 B
- 脚本assets/reader.js23.9 KB
- 资产文件assets/styles/novel-theme-base.css1013 B
- 资产文件assets/styles/novel-theme-components.css3.8 KB
- 资产文件assets/styles/novel-theme-content.css2.9 KB
- 资产文件assets/styles/novel-theme-header.css3.9 KB
- 资产文件assets/styles/novel-theme-mermaid.css3.1 KB
- 资产文件assets/styles/novel-theme-overlays.css3.6 KB
- 资产文件assets/styles/novel-theme-responsive.css4.5 KB
- 资产文件assets/styles/novel-theme-sidebar.css6.2 KB
- 资产文件assets/styles/novel-theme-variables.css1.4 KB
- 资产文件assets/template.html6.0 KB
- 参考文档package.json352 B
- 参考文档references/reader-experience.md625 B
- 参考文档references/reader-operations.md1.1 KB
- 脚本scripts/lib/http-server.cjs11.4 KB
- 脚本scripts/lib/markdown-renderer.cjs9.7 KB
- 脚本scripts/lib/plan-navigator.cjs10.1 KB
- 脚本scripts/lib/plan-table-parser.cjs9.9 KB
- 脚本scripts/lib/port-finder.cjs1.2 KB
- 脚本scripts/lib/process-mgr.cjs3.7 KB
- 脚本scripts/server.cjs9.6 KB
03 SKILL.md 正文
Write Functional
This skill is a domain specialization of the core
writeskill (cnos.core/skills/write/SKILL.md). It applies the verb-and-style convention:writegoverns writing acts in general;write-functionalnarrows that to writing code in functional style.
Core Principle
Pure core, effects at edges.
Business logic is pure functions. I/O, state, and time live at the boundary. The pure core is trivially testable; the effectful shell is thin and auditable.
1. Purity
1.1 Isolate Effects (see also: code §2.3)
❌ parse_and_write(path) -- mixed
✅ content |> parse |> write -- separated
1.2 Return, Don't Mutate
❌ let count = ref 0 in ... incr count
✅ let rec loop acc = ... loop (acc + 1)
1.3 Localize Mutable State
When mutation is necessary (e.g., parsers), contain it:
(* State doesn't escape — API is pure *)
type state = { src: string; mutable pos: int }
let parse s =
let st = { src = s; pos = 0 } in
parse_value st (* returns Result, no state leaks *)
Case study: cn_json.ml — full JSON parser using localized mutable pos.
API is parse : string -> (t, string) result — pure. Internally uses
{ src; mutable pos } for efficient single-pass parsing. Errors return
position info: Error (sprintf "expected X at pos %d" st.pos).
2. Composition
2.1 Pipelines Over Sequences
❌ let a = f x in let b = g a in h b
✅ x |> f |> g |> h
2.2 Small Functions That Compose
❌ process_everything(input)
✅ input |> validate |> transform |> emit
2.3 Map/Filter/Fold Over Loops
❌ for i = 0 to n do ... done
✅ List.map f items
✅ List.filter_map extract items (* filter + map in one pass *)
✅ List.fold_left combine init items
3. Types as Constraints
3.1 Closed Sum Types
Make invalid states unrepresentable:
❌ type status = string
✅ type status = Pending | Active | Closed
3.2 Semantic Newtypes
❌ let send (to_: string) (msg: string) = ...
✅ type peer_id = PeerId of string
let send (PeerId to_) (msg: string) = ...
3.3 Result Over Exceptions
❌ raise (Parse_error "unexpected")
✅ Error (Printf.sprintf "expected X at pos %d" pos)
3.4 Option Over Null Checks
❌ if x = "" then ... else ...
✅ match find key map with Some v -> ... | None -> ...
4. Error Handling
4.1 Explicit Error Paths
(* Every function that can fail returns Result *)
let parse s : (value, string) result = ...
let load path : (config, string) result = ...
4.2 Early Return Pattern
match step1 () with
| Error e -> Error e
| Ok a ->
match step2 a with
| Error e -> Error e
| Ok b -> Ok (finish b)
Or with bind:
let ( let* ) = Result.bind in
let* a = step1 () in
let* b = step2 a in
Ok (finish b)
4.3 Fun.protect for Cleanup
let read path =
let ic = open_in path in
Fun.protect ~finally:(fun () -> close_in_noerr ic) (fun () ->
really_input_string ic (in_channel_length ic))
5. Testing
5.1 Pure Functions Are Trivially Testable
No mocking, no setup, no teardown:
let%expect_test "parse null" =
match parse "null" with
| Ok Null -> print_endline "null"
| _ -> print_endline "FAIL";
[%expect {| null |}]
5.2 Test the Pure Core Exhaustively
Effects are thin wrappers — test them minimally. Pure logic gets full coverage.
Anti-Patterns
| Anti-Pattern | Fix |
|---|---|
ref for accumulation |
Recursive loop with accumulator |
for/while loops |
List.map, fold_left, recursion |
| Exception for control flow | Result or Option |
Option.get / List.hd |
Pattern match explicitly |
| Mixed pure/effectful | Separate into core/shell |
| String for everything | Sum types, newtypes |
When to Break Rules
- Performance-critical hot paths — mutation may be necessary
- Parser internals — mutable pos is fine if API is pure
- FFI boundaries — imperative style may be clearer
Document the exception. Contain it. Don't let it leak.
04 同仓库更多 Skills
Issue 分诊与判定
issues/triage
Issue 分诊规则指引。在对新 issue 进行分类、判定其是否符合派发条件,或决定将其关闭/取代/延后时使用。
Issue 标签分类体系
issues/taxonomy
Issue 标签分类体系指引。在对 issue 的 kind/area/priority/effort/status/protocol/dispatch 标签进行分类,或看板需要解读这些标签时使用。
issues/map
Issue-board (Issue Pivot) generation domain. Use when reasoning about `cn issues map`'s fetch, taxonomy-parse, effort-computation, and render pipeline, or about the board's JSON/HTML output contract.
issues
cnos.issues package entrypoint. Use when reasoning about issue taxonomy, the Issue Pivot / issue-board (`cn issues map`), the read-only CDS issue-state evaluator (`cn issues fsm evaluate`), or the current command-dispatch disposition of issue tooling.
receipt-stream
Cross-cycle receipt-stream doctrine for protocol-iteration. Use when γ closes a cycle and writes the per-cycle iteration artifact (`cdd-iteration.md`), when γ updates the cross-cycle aggregator at `.cdd/iterations/INDEX.md`, when ε reads the receipt stream across cycles to surface protocol-gap patterns, when a finding's disposition lands a cross-repo patch and the cross-repo trace bundle attaches, or when a courtesy empty-findings stub is written for a `protocol_gap_count == 0` cycle.
mid-flight
Mid-flight γ→in-flight-α rescue channel. Use when γ needs to change a load-bearing fact (pinned axis, scope, AC, blocker) after α has begun coding, when γ edits the cycle's GitHub issue body mid-cycle, or when a spec change lands on origin/main while α/β polling sessions are in-flight.