Skip to content

Commit a2e3ef6

Browse files
committed
Fixes Result while loops
1 parent 0409175 commit a2e3ef6

File tree

2 files changed

+26
-14
lines changed

2 files changed

+26
-14
lines changed

src/FsToolkit.ErrorHandling/ResultCE.fs

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -74,19 +74,16 @@ module ResultCE =
7474
[<InlineIfLambda>] guard: unit -> bool,
7575
[<InlineIfLambda>] generator: unit -> Result<unit, 'error>
7676
) : Result<unit, 'error> =
77-
if guard () then
78-
let mutable whileBuilder = Unchecked.defaultof<_>
79-
80-
whileBuilder <-
81-
fun () ->
82-
this.Bind(
83-
this.Run generator,
84-
(fun () -> if guard () then this.Run whileBuilder else this.Zero())
85-
)
86-
87-
this.Run whileBuilder
88-
else
89-
this.Zero()
77+
78+
let rec whileBuilder =
79+
fun () ->
80+
if guard () then
81+
this.Bind(this.Run(fun () -> generator ()), (fun () -> this.Run(fun () -> whileBuilder ())))
82+
else
83+
this.Zero()
84+
85+
this.Run(fun () -> whileBuilder ())
86+
9087

9188
member inline this.For
9289
(

tests/FsToolkit.ErrorHandling.Tests/ResultCE.fs

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -236,15 +236,30 @@ let ``ResultCE loop Tests`` =
236236
testCase "while"
237237
<| fun () ->
238238
let data = 42
239-
let mutable index = 0
239+
let maxLoop = 10
240+
let mutable index = maxLoop
240241

241242
let actual = result {
242243
while index < 10 do
243244
index <- index + 1
244245

245246
return data
246247
}
248+
Expect.equal index maxLoop "index should match maxLoop"
249+
Expect.equal actual (Result.Ok data) "Should be ok"
250+
testCase "while long"
251+
<| fun () ->
252+
let data = 42
253+
let mutable index = 0
254+
let maxLoop = 1000000
255+
let actual = result {
256+
while index < maxLoop do
257+
index <- index + 1
258+
259+
return data
260+
}
247261

262+
Expect.equal index (maxLoop ) "index should match maxLoop"
248263
Expect.equal actual (Result.Ok data) "Should be ok"
249264
testCase "for in"
250265
<| fun () ->

0 commit comments

Comments
 (0)