作为使用策略模式的项目的一部分,我尝试编写一个函数,该函数创建一个函数,该函数在每次应用时返回无限序列的下一个值。目前,我使用的是这个不可靠的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?什么是正确/优雅的方式,以实现广泛的序列表达式,可以注入到这样的战略框架?
编辑后,费奥多索金的回答序列表达吸引我在目前,因为他们帮助我思考的问题,我正在看。我不想使用可变的命令式样式代码,而是使用更复杂的输入序列构建此模式。
发布于 2015-10-12 23:53:36
您注意到从来没有释放枚举数吗?这就是为什么没有Seq.next:它的使用需要不合理的设计。
至于第二个问题,还不完全清楚您要实现的“这个”是什么。就我从代码中收集到的信息而言,您正在尝试生成一个生成1.0或0.0的“有状态过程”,每次调用它时都会切换。对吗?
如果是这样的话,我将通过一个可变的值来实现它。比顺序少得多的开销:
let FunctionFactory<'T> =
let mutable flag = true
fun (_:'T) ->
flag <- not flag
if flag then 1.0 else 0.0https://stackoverflow.com/questions/33091526
复制相似问题