-
Hello I was reading through the v5 blog posts, specifically the validation, but got lost on the part:
Could someone please breakdown the My current understanding: A function is made for currying, the first parameter But I don't understand the third one. The CVV creation action is passed as arg to the fun? It will run on the result of the currying, when .As() is called? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Also it's not clear how to enact on the validation result. E.g. I was copying how I would do for an ValidateCVV("123")
.Match(
ex => // why ex is string not error?
{
Console.WriteLine($"Error: {ex}");
return 1;
},
_ => 0); But the signatures don't match. How can I get the errors? I looked at the sample, but it just writes the object to console: https://github.com/louthy/language-ext/blob/main/Samples/CreditCardValidation/Program.cs |
Beta Was this translation helpful? Give feedback.
-
You can also write it like this: fun((int code, string _) => new CVV(code)) Which might be a bit clearer. Essentially, we're forcing C#'s type system to infer the lambda. The lambda needs to be coerced into being a It's the equivalent of: new Func<int, string, CVV>((code, _) => new CVV(code))
Correct
Correct
Correct
The third parameter is the return-type. The
There are a number of ways of extracting the results. public abstract B Match<B>(Func<A, B> Succ, Func<F, B> Fail);
public Unit Match(Action<A> Succ, Action<F> Fail) =>
Match(fun(Succ), fun(Fail)); The first one is the one that you want. The second one just fires off an In your example, the reason why the first one isn't an error is because that's the success delegate. The second delegate is for catching the failure. ValidateCVV("123")
.Match(
ex => // why ex is string not error?
{
Console.WriteLine($"Error: {ex}");
return 1;
},
_ => 0); It's good practice to used named parameters: ValidateCVV("123").Match(
Succ: cvv => 0,
Fail: ex =>
{
Console.WriteLine($"Error: {ex}");
return 1;
}); This then looks like regular pattern-matching, is easier for others to read, and allows you to write the parameters in any order you like. You can also use regular C# pattern-matching: var res = ValidateCVV("123") switch
{
Validation.Success<Error, CVV> (var cvv) => $"Success {cvv}",
Validation.Fail<Error, CVV> (var error) => $"Failure {error}"
};
I should probably update that! |
Beta Was this translation helpful? Give feedback.
You can also write it like this:
Which might be a bit clearer. Essentially, we're forcing C#'s type system to infer the lambda. The lambda needs to be coerced into being a
Func<int, string, CVV>
. Thefun
function does that.It's the equivalent of:
Correct
Correct
Correct
The third parameter is the return-type. The
C…