Skip to content

Commit

Permalink
Merge pull request #333 from daniel-chambers/fix-loops-in-maybe
Browse files Browse the repository at this point in the history
Bugfix for loops in the maybe computation expression
  • Loading branch information
panesofglass committed Nov 17, 2015
2 parents 0af75e9 + 64706fd commit 8f87218
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/FSharpx.Extras/ComputationExpressions/Monad.fs
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,9 @@ module Option =
this.TryFinally(body res, fun () -> match res with null -> () | disp -> disp.Dispose())

member this.While(guard, f) =
if not (guard()) then this.Zero() else
this.Bind(f(), fun _ -> this.While(guard, f))
if not (guard()) then Some () else
do f() |> ignore
this.While(guard, f)

member this.For(sequence:seq<_>, body) =
this.Using(sequence.GetEnumerator(),
Expand Down
24 changes: 24 additions & 0 deletions tests/FSharpx.Tests/MaybeTest.fs
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,27 @@ let ``monadplus laws``() =
fun a b -> mplus (ret a) b = ret a
// fsCheck "left distribution" <|
// fun a b f -> (mplus a b >>= f) = (mplus (a >>= f) (b >>= f))

[<Test>]
let ``for loops enumerate entire sequence and subsequent expressions also run``() =
let count = ref 0
let result = maybe {
for i in [1;2;3] do
incr count
return true
}

!count |> should equal 3
result |> should equal (Some true)

[<Test>]
let ``while loops execute until guard is false and subsequent expressions also run``() =
let count = ref 0
let result = maybe {
while !count < 3 do
incr count
return true
}

!count |> should equal 3
result |> should equal (Some true)

0 comments on commit 8f87218

Please sign in to comment.