F#のシーケンスを使用して計算を強制するための最も慣用のスタイルは何ですか?

StackOverflow https://stackoverflow.com//questions/9631683

  •  10-12-2019
  •  | 
  •  

質問

私は副作用的な操作を持っています

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

コードが実行させる最も慣用の方法は何ですか?

私はseq.doitを書いたが、それはかゆみ

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

役に立ちましたか?

解決

Deferred sequences are used when you create sequences using Seq.delay or sequence expression seq{}. Any function on sequence returning any datatype other than seq can force computation.

Alternatively, you can use for loop instead of Seq.iter:

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

If you want to hide side effects and return request for later use, Seq.fold is a good choice:

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

他のヒント

I think Seq.iter is appropriate in this case. From the MSDN reference page:

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

Applies the given function to each element of the collection.

So, supposing that request.Append does not return anything, your code becomes:

securities |> Seq.iter (fun x -> request.Append("securities", x))
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top