Skip to content

Commit a637fdd

Browse files
committed
Correctly implement For for TaskOption
1 parent 5c2e186 commit a637fdd

File tree

2 files changed

+25
-10
lines changed

2 files changed

+25
-10
lines changed

src/FsToolkit.ErrorHandling.TaskResult/TaskOptionCE.fs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -418,12 +418,20 @@ type TaskOptionBuilderBase() =
418418
true)
419419
)
420420

421-
member inline _.For
421+
member inline this.For
422422
(
423423
sequence: seq<'T>,
424424
body: 'T -> TaskOptionCode<'TOverall, unit>
425425
) : TaskOptionCode<'TOverall, unit> =
426-
ResumableCode.For(sequence, body)
426+
ResumableCode.Using(
427+
sequence.GetEnumerator(),
428+
// ... and its body is a while loop that advances the enumerator and runs the body on each element.
429+
(fun e ->
430+
this.While(
431+
(fun () -> e.MoveNext()),
432+
TaskOptionCode<'TOverall, unit>(fun sm -> (body e.Current).Invoke(&sm))
433+
))
434+
)
427435

428436
member inline internal this.TryFinallyAsync
429437
(

tests/FsToolkit.ErrorHandling.TaskResult.Tests/TaskOptionCE.fs

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -391,28 +391,35 @@ let ceTests =
391391
task {
392392

393393
let mutable loopCount = 0
394-
let expected = Error "error"
394+
let mutable wasCalled = false
395+
396+
let sideEffect () =
397+
wasCalled <- true
398+
"ok"
399+
400+
let expected = None
395401

396402
let data =
397-
[ Ok "42"
398-
Ok "1024"
403+
[ Some "42"
404+
Some "1024"
399405
expected
400-
Ok "1M"
401-
Ok "1M"
402-
Ok "1M" ]
406+
Some "1M"
407+
Some "1M"
408+
Some "1M" ]
403409

404410
let! actual =
405-
taskResult {
411+
taskOption {
406412
for i in data do
407413
let! x = i
408414
loopCount <- loopCount + 1
409415
()
410416

411-
return "ok"
417+
return sideEffect ()
412418
}
413419

414420
Expect.equal loopCount 2 "Should only loop twice"
415421
Expect.equal actual expected "Should be an error"
422+
Expect.isFalse wasCalled "No additional side effects should occur"
416423
} ]
417424

418425
let specialCaseTask returnValue =

0 commit comments

Comments
 (0)