Idiomatic F# for iterating a seq and mapping whenever changes occur on a given selection I've written a function that takes a sequence and check for every item in that sequence whether the current value a selection (obtained with a selection function) is different (or on the first iteration) from the previous computed value and if that's the case (we considered there is a change), then map the current item and returns a new mapped item along the current item.

If there is no change the sequence keeps returning the current item and the last mapped item detected due to a change.

let differentOrNew option currentValue =
    match option with
    | Some value when currentValue &lt;&gt; value -&gt;
        true
    | Some _ -&gt;
        false
    | None -&gt;
        true

let def&lt;'T&gt; =
    Unchecked.defaultof&lt;'T&gt;

let mapChange selector mapping seq =
    let mutable previous = None
    let mutable change = def

    seq
    |&gt; Seq.map(fun item -&gt;
        let currentValue = selection item
        if differentOrNew previous currentValue then
            previous &lt;- Some currentValue
            change &lt;- mapping item
        item, change)
    |&gt; Seq.map(fun state -&gt; fst state, snd state)


That code works, but it's clearly not the best idiomatic piece of F# code I've ever seen. 

I am wondering how to get something more "F#-idiomatic".
|&gt; Seq.map(fun state -&gt; fst state, snd state)


I think this last operation is unnecessary as it is a map from 'a * 'b to 'a * 'b (fst returns the first element in the tuple and snd the second).



If you want to get rid of the mutable variables, you can use Seq.mapFold instead:

let mapChange selector mapping seq = 
    seq
    |&gt; Seq.mapFold (fun (previous, change) item -&gt;
        let currentValue = selector item
        match differentOrNew previous currentValue with
        | true -&gt; 
            let newChange = mapping item
            (item, newChange), (Some currentValue, newChange)
        | false -&gt; 
            (item, change), (previous, change)
    ) (None, def)
    |&gt; (fst)