使用F#中的序列强制计算的最惯用的风格是什么?
题
我有一个副有效的操作
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))
不隶属于 StackOverflow