Seq.iter vs for - what difference?

For most of the situations, they are the same. I would prefer the first use. It looks clear to me.

The difference is that for in loop support IEnumerable objects, while Seq.iter requires that your collection (linq.deltas) is IEnumerable<T>.

E.g. MatchCollection class in .net regular expression inherits IEnumerable not IEnumerable<T>, you cannot use Seq.map or Seq.iter directly on it. But you can use for in loop.


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

You can modify mutable variables from the body of a for loop. You can't do that from a closure, which implies you can't do that using iter. (Note: I'm talking about mutable variables declared outside of the for / iter. Local mutable variables are accessible.)

Considering that the point of iter is to perform some side effect, the difference can be important.

I personally seldom use iter, as I find for to be clearer.

Tags:

F#