Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added an extension method for C# to convert an FSharpOption into a Result #35

Merged
merged 3 commits into from
Jan 17, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions src/Chessie/ErrorHandling.fs
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,12 @@ type ResultExtensions () =
/// Otherwise the exisiting error messages are propagated.
[<Extension>]
static member inline Join (this: Result<'TOuter, 'TMessage>, inner: Result<'TInner, 'TMessage>, _outerKeySelector: Func<'TOuter,'TKey>, _innerKeySelector: Func<'TInner, 'TKey>, resultSelector: Func<'TOuter, 'TInner, 'TResult>) =
let curry func = fun a -> fun b -> func (a, b)
let curry func = fun a b -> func (a, b)
curry resultSelector.Invoke
<!> this
<*> inner
<*> inner

/// Converts an option into a Result.
[<Extension>]
static member ToResult(this, msg) =
this |> failIfNone msg
25 changes: 25 additions & 0 deletions tests/Chessie.CSharp.Test/ExtensionsTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using Chessie.ErrorHandling;
using Chessie.ErrorHandling.CSharp;
using Microsoft.FSharp.Core;
using NUnit.Framework;

namespace Chessie.CSharp.Test
Expand Down Expand Up @@ -58,5 +59,29 @@ from c in r3
ifSuccess: (s, _) => Assert.Fail("should fail"),
ifFailure: list => Assert.That(list, Is.EquivalentTo(new[] { "fail1" })));
}

[Test]
public void ToResultOnSomeShouldSucceed()
{
var opt = FSharpOption<int>.Some(42);
var result = opt.ToResult("error");
result.Match(
ifSuccess: (x, msgs) =>
{
Assert.AreEqual(42, x);
Assert.That(msgs, Is.Empty);
},
ifFailure: errs => Assert.Fail());
}

[Test]
public void ToResultOnNoneShoulFail()
{
var opt = FSharpOption<int>.None;
var result = opt.ToResult("error");
result.Match(
ifSuccess: (x, _) => Assert.Fail(),
ifFailure: errs => Assert.That(errs, Is.EquivalentTo(new[] {"error"})));
}
}
}