Skip to content

Instantly share code, notes, and snippets.

@dungpa
Created September 13, 2012 19:43
Show Gist options
  • Save dungpa/3717063 to your computer and use it in GitHub Desktop.
Save dungpa/3717063 to your computer and use it in GitHub Desktop.
Common mistake
let plusOne (s : seq<_>) =
let e = s.GetEnumerator()
seq {
while e.MoveNext() do
yield e.Current + 1
}
let r = plusOne [1; 2; 3]
printfn "%A" r // prints [2; 3; 4]
printfn "%A" r // prints []
// The variable e is immutable but contains mutable state.
// The above function is mutating captured state
// while the below function is mutating state that wasn't captured.
let plusOneCorrect (s : seq<_>) =
seq {
let e = s.GetEnumerator()
while e.MoveNext() do
yield e.Current + 1
}
let r = plusOneCorrect [1; 2; 3]
printfn "%A" r // prints [2; 3; 4]
printfn "%A" r // prints [2; 3; 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment