Alex Rivera | Logout

Seq.iter vs for - what difference?

Asked 2011-04-20T06:53:40.437
15

I can do

for event in linq.Deltas do

or I can do

linq.Deltas |> Seq.iter(fun event ->

So I'm not sure if that is the same. If that is not the same I want to know the difference. I don't know what to use: iter or for.

added - so if that is the matter of choice I prefer to use iter on a top level and for is for closures

added some later - looking like iter is map + ignore - it's the way to run from using imperative ignore word. So it's looking like functional way ...

f#
Edit
Report

1 Answer

19

As others mentioned, there are some differences (iter supports non-generic IEnumerator and you can mutate mutable values in for). These are sometimes important differences, but most of the times you can freely choose which one to use.

I generally prefer for (if there is a language construct, why not use it?). The cases where iter looks nicer are when you have a function that you need to call (e.g. using partial application):

// I would write this:
strings |> Seq.iter (printfn "%c")

// instead of:
for s in strings do printfn "%c" s

Similarly, using iter is nicer if you use it at the end of some processing pipeline:

// I would write this:
inputs |> Seq.filter (fun x -> x > 0)
       |> Seq.iter (fun x -> foo x)

// instead of:
let filtered = inputs |> Seq.filter (fun x -> x > 0)
for x in filtered do foo x
answered 2011-04-20T10:35:35.857

Your Answer