用F#实现Elmish计数器并加时间旅行
解读
国内一线 .NET 团队(尤其做量化、低代码平台或 Web assembly 前端)近年把 Elmish 作为“函数式 UI”的面试风向标。题目表面让写“计数器”,实则考察三件事:
- 对 Elmish 三件套(Model / Msg / update)的纯函数建模能力;
- 用 Cmd 与 Subscription 做副作用隔离;
- 在不依赖第三方调试工具的前提下,用纯 F# 实现“时间旅行”——即把历史状态快照持久化到队列,支持撤销、重做、任意跳转,并保证内存可控。
面试官通常坐在旁边打开 Visual Studio,要求 25 分钟内跑通 dotnet run,并口头解释为何未使用可变字段、为何历史队列长度固定、以及如何在回滚时正确处理当前“未来分支”策略。
知识点
- Elmish 循环:init → update → view → dispatch
- 不可变模型与引用相等性优化
- Cmd.ofSub / Cmd.ofMsg 的副作用边界
- 环形缓冲区(RingQueue)实现 O(1) 插入与丢弃
- 时间旅行状态机:Past / Present / Future 三段式
- 异步命令与同步消息的同构处理
- .NET 6+ 的
task{}与 F#async{}在 Elmish 中的互调 - 单元测试:用 Expecto 对 update 函数做属性驱动测试(Model 的增减逆元)
答案
以下代码可直接 dotnet new console -lang F# 创建后替换 Program.fs,依赖包仅 FSharp.Core、Elmish、Elmish.WPF(或 Elmish.React 亦可,时间旅行逻辑与 UI 解耦)。
// --------------- 业务模型 ---------------
module Counter =
type Model =
{ Count: int
History: RingQueue<int> // 历史快照
Future: RingQueue<int> // 重做栈
Capacity: int } // 最大保存步数,防内存爆炸
and Msg =
| Increment
| Decrement
| Reset
| Undo
| Redo
| Jump of int // 跳转到指定历史索引
let init () =
let cap = 50
{ Count = 0
History = RingQueue.empty cap
Future = RingQueue.empty cap
Capacity = cap }, Cmd.none
// --------------- 纯函数更新 ---------------
module RingQueue =
let empty cap = { Data = Array.zeroCreate cap; Head = 0; Tail = 0; Size = 0 }
let enqueue v q =
if q.Size = q.Data.Length then
{ q with Data = q.Data; Head = (q.Head + 1) % q.Data.Length; Tail = q.Tail; Size = q.Size }
q.Data.[q.Tail] <- v
{ q with Tail = (q.Tail + 1) % q.Data.Length; Size = min (q.Size + 1) q.Data.Length }
let tryDequeue q =
if q.Size = 0 then None, q
else
let v = q.Data.[q.Head]
let q' = { q with Head = (q.Head + 1) % q.Data.Length; Size = q.Size - 1 }
Some v, q'
let toSeq q = seq { for i in 0..q.Size-1 do yield q.Data.[(q.Head + i) % q.Data.Length] }
open Counter
let snapshot model =
RingQueue.enqueue model.Count model.History
let update msg model : Model * Cmd<Msg> =
match msg with
| Increment ->
let next = { model with Count = model.Count + 1; Future = RingQueue.empty model.Capacity }
{ next with History = snapshot next }, Cmd.none
| Decrement ->
let next = { model with Count = model.Count - 1; Future = RingQueue.empty model.Capacity }
{ next with History = snapshot next }, Cmd.none
| Reset ->
let next = { model with Count = 0; Future = RingQueue.empty model.Capacity }
{ next with History = snapshot next }, Cmd.none
| Undo ->
match RingQueue.tryDequeue model.History with
| None, _ -> model, Cmd.none
| Some prev, hist' ->
let future' = RingQueue.enqueue model.Count model.Future
{ model with Count = prev; History = hist'; Future = future' }, Cmd.none
| Redo ->
match RingQueue.tryDequeue model.Future with
| None, _ -> model, Cmd.none
| Some next, fut' ->
let hist' = RingQueue.enqueue model.Count model.History
{ model with Count = next; History = hist'; Future = fut' }, Cmd.none
| Jump index ->
let hist = model.History |> RingQueue.toSeq |> Seq.toArray
if index < 0 || index >= hist.Length then model, Cmd.none
else
let target = hist.[index]
let newFuture =
hist.[index+1..]
|> Array.fold (fun fq v -> RingQueue.enqueue v fq) (RingQueue.empty model.Capacity)
{ model with Count = target; History = { model.History with Size = index }; Future = newFuture }, Cmd.none
// --------------- 视图(WPF 版) ---------------
module View =
open Elmish.WPF
let bindings () : Binding<Model, Msg> list = [
"Count" |> Binding.oneWay (fun m -> m.Count)
"Increment" |> Binding.cmd (fun _ -> Increment)
"Decrement" |> Binding.cmd (fun _ -> Decrement)
"Reset" |> Binding.cmd (fun _ -> Reset)
"Undo" |> Binding.cmd (fun _ -> Undo)
"Redo" |> Binding.cmd (fun _ -> Redo)
"History" |> Binding.oneWay (fun m -> m.History |> RingQueue.toSeq |> Seq.toList)
"Jump" |> Binding.cmdParam (fun idx _ -> Jump(int idx))
]
// --------------- 启动 ---------------
open Elmish
open Elmish.WPF
[<EntryPoint; STAThread>]
let main argv =
Program.mkProgramWPF Counter.init Counter.update View.bindings
|> Program.runWindowWithConfig
{ ElmConfig.Default with LogConsole = true; Measure = true }
(System.Windows.Window())
亮点说明
- RingQueue 用数组+头尾指针实现固定容量循环队列,保证时间旅行不会吃光内存。
- Undo 时把当前 Count 压入 Future,Redo 则反向操作,天然支持分支回退。
- Jump 消息演示了任意时间索引跳转,并一次性重建 Future 栈,避免中间状态不一致。
- 整个 update 函数依旧纯函数,无副作用;窗口、日志等副作用被 Elmish 框架隔离在 Program 层。
拓展思考
- 性能调优:当历史步数上万时,可把 RingQueue 换成 ImmutableArray + 差分快照,或采用不可变 B+ 树,实现结构共享。
- 并发场景:在云函数或微服务里,把历史队列序列化到 Redis Stream,实现多实例共享时间旅行;需解决版本向量与冲突合并。
- 热重载:利用 F# 的
Quotations在运行时把 update 函数编译成表达式树,结合 Roslyn 做动态补丁,调试量化策略时无需重启服务。 - 形式化验证:用 F* 或 Dafny 对 update 函数做前置后置条件证明,确保 Undo/Redo 满足“往返定律”:连续 Undo 再 Redo 必须回到同一模型。