【问题标题】:What is the most idiomatic style to force a computation using Sequences in f#?在 f# 中强制使用序列进行计算的最惯用的风格是什么?
【发布时间】:2012-03-09 09:27:27
【问题描述】:

我有一个副作用手术

     securities |> Seq.map (fun x -> request.Append("securities",x))

让代码执行最惯用的方式是什么?

我写了一个 Seq.Doit,但它很痒

  module Seq =
     let Doit sa = sa |> Seq.toArray |> ignore

【问题讨论】:

    标签: arrays f# sequences deferred


    【解决方案1】:

    我认为Seq.iter 在这种情况下是合适的。从 MSDN 参考页面:

    Seq.iter : ('T -> unit) -> seq<'T> -> unit
    

    将给定函数应用于集合的每个元素。

    所以,假设 request.Append 不返回任何内容,您的代码变为:

    securities |> Seq.iter (fun x -> request.Append("securities", x))
    

    【讨论】:

    • 观察得很好。 map + doit = iter
    • 请注意,seq 的计算会被实际延迟,直到将 seq 转换为列表/数组或将其从 seq 类型中删除的东西之后
    【解决方案2】:

    当您使用 Seq.delay 或序列表达式 seq{} 创建序列时,会使用延迟序列。序列上的任何函数返回除seq 之外的任何数据类型都可以强制计算。

    或者,您可以使用for 循环而不是Seq.iter

    for s in securities do
       request.Append("securities", s)
    

    如果你想隐藏副作用并返回request供以后使用,Seq.fold是一个不错的选择:

    securities |> Seq.fold (fun acc x -> acc.Append("securities", x); acc) request
    

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 2018-03-06
      • 2011-11-19
      • 1970-01-01
      • 2014-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多