F# Seq.next - 正确的模式是什么?
F# Seq.next - what's the correct pattern?
作为使用策略模式的项目的一部分,我正在尝试编写一个函数,它创建一个函数,每次应用它时 returns 都是无限序列的下一个值。目前我正在使用这个狡猾的 GetNext 函数来做这件事:
let GetNext<'T> (enumerator:System.Collections.Generic.IEnumerator<'T>) =
let n = enumerator.MoveNext()
enumerator.Current
let FunctionFactory<'T> =
let s = 0.0 |> Seq.unfold (fun i -> Some(i, if 0.0 = i then 1.0 else 0.0))
let enumerator = s.GetEnumerator()
(fun (ignoredParam:'T) -> GetNext enumerator )
我希望 FunctionFactory 看起来像这样:
let FunctionFactory<'T> =
let s = 0.0 |> Seq.unfold (fun i -> Some(i, if 0.0 = i then 1.0 else 0.0))
(fun (ignoredParam:'T) -> Seq.next s )
ignoredParam 用于其他函数,这些函数通过相同的策略模式并取决于它提供的上下文。由于这看起来很糟糕,我真的有两个问题。为什么没有 Seq.next?什么是 correct/elegant 实现 可以注入策略框架的各种序列表达式的方法,例如 这个?
根据 Fyodor Soikin 的回答进行编辑 - 序列表达式目前对我很有吸引力,因为它们可以帮助我思考我正在研究的问题。我不想使用可变的命令式代码,而是使用更复杂的输入序列构建此模式。
您是否注意到您从不处理枚举器?
这就是为什么没有 Seq.next
的原因:它的使用需要不合理的设计。
至于第二个问题,还不完全清楚您要实现的 "this" 是什么。据我从代码中收集到的信息,您正在尝试生成一个 "stateful procedure",它将产生 1.0 或 0.0,每次调用时都会切换。对吗?
如果是这样,我会通过可变值来实现。比序列少很多开销:
let FunctionFactory<'T> =
let mutable flag = true
fun (_:'T) ->
flag <- not flag
if flag then 1.0 else 0.0
作为使用策略模式的项目的一部分,我正在尝试编写一个函数,它创建一个函数,每次应用它时 returns 都是无限序列的下一个值。目前我正在使用这个狡猾的 GetNext 函数来做这件事:
let GetNext<'T> (enumerator:System.Collections.Generic.IEnumerator<'T>) =
let n = enumerator.MoveNext()
enumerator.Current
let FunctionFactory<'T> =
let s = 0.0 |> Seq.unfold (fun i -> Some(i, if 0.0 = i then 1.0 else 0.0))
let enumerator = s.GetEnumerator()
(fun (ignoredParam:'T) -> GetNext enumerator )
我希望 FunctionFactory 看起来像这样:
let FunctionFactory<'T> =
let s = 0.0 |> Seq.unfold (fun i -> Some(i, if 0.0 = i then 1.0 else 0.0))
(fun (ignoredParam:'T) -> Seq.next s )
ignoredParam 用于其他函数,这些函数通过相同的策略模式并取决于它提供的上下文。由于这看起来很糟糕,我真的有两个问题。为什么没有 Seq.next?什么是 correct/elegant 实现 可以注入策略框架的各种序列表达式的方法,例如 这个?
根据 Fyodor Soikin 的回答进行编辑 - 序列表达式目前对我很有吸引力,因为它们可以帮助我思考我正在研究的问题。我不想使用可变的命令式代码,而是使用更复杂的输入序列构建此模式。
您是否注意到您从不处理枚举器?
这就是为什么没有 Seq.next
的原因:它的使用需要不合理的设计。
至于第二个问题,还不完全清楚您要实现的 "this" 是什么。据我从代码中收集到的信息,您正在尝试生成一个 "stateful procedure",它将产生 1.0 或 0.0,每次调用时都会切换。对吗?
如果是这样,我会通过可变值来实现。比序列少很多开销:
let FunctionFactory<'T> =
let mutable flag = true
fun (_:'T) ->
flag <- not flag
if flag then 1.0 else 0.0