views:

91

answers:

2
mySequence
|> Seq.iteri (fun i x -> ...)
...

How do I bind i at the end of the sequence? In other words how do I bind the value representing the number of iterations iterated by iteri?

Of course I could create a ref and assign i for all iterations, but I wonder if there is a more elegant way?

+3  A: 

You could use fold, so that

Seq.iteri (fun i x -> ...)

becomes

Seq.fold (fun i x -> ... ; i+1) 0

along these lines:

let aSeq = 
    seq {
        for i in 1..10 do
            printfn "eval %d" i
            yield i
    }

let r = 
    aSeq 
    |> Seq.fold (fun i x ->
        printfn "iter %d" x // or whatever is "..."
        i+1) 0     

printfn "result: %d" r
Brian
For me Folds are one of the functional idioms that has really changed the way I approach problem solving. You should spend some time with them if you can Moonlight.
gradbot
Thank you gradbot, I appreciate the encouragement!
Moonlight
A: 

As I understand you could just use function that will directly return length of the sequence that is passed to Seq.iteri (since Seq.iteri will iterate over the whole sequence). This will be more functional programming way instead of thinking about mutable variables:

Seq.length mySequence

In your case:

mySequence |> Seq.iteri (fun i x -> ...)
let i = Seq.length mySequence
The_Ghost