CSharpFunctionalExtensions
CSharpFunctionalExtensions copied to clipboard
[Enhancement] KeyValuePair-Deconstruction on Match
Hi,
currently, for me and with the build in functions, it is impossible to deconstruct a Maybe<KeyValuePair<K,V>>
in their <K, V> with
the Match
-function in one step.
As an example:
I've the following code:
var maybe = Maybe<KeyValuePair<int, string>>.From(new KeyValuePair<int, string>(1, "A"));
What work per default:
var ret = maybe.Match(
kv => kv.Key,
() => -1);
But, and thats always as syntactic sugar, with c# 7 we can deconstruct a kv on the fly, so i´ts very nice, to deconstruct the kv in one step with the match. I build my own method which will do that, so it might be an idea to put this one in this project if any need. Here's my code for the extended Match:
For <TOut> Match
:
public static TOut Match<TOut, TKey, TValue>(this Maybe<KeyValuePair<TKey, TValue>> kvOpt,
Func<TKey, TValue, TOut> some, Func<TOut> none) =>
kvOpt.HasValue ? some.Invoke(kvOpt.Value.Key, kvOpt.Value.Value) : none.Invoke();
For void Match
:
public static void Match<TKey, TValue>(this Maybe<KeyValuePair<TKey, TValue>> maybe, Action<TKey, TValue> Some,
Action None)
{
if (maybe.HasValue)
{
Some.Invoke(maybe.Value.Key, maybe.Value.Value);
}
else
{
None.Invoke();
}
}
And for an usage example:
var ret = maybe.Match(
(intVal, stringVal) => intVal,
() => -1);
I've checked out your project and implement code an tests, but cannot release a pull request (access denied). Is it possible to become a contributor to the project?
Regards, Laszlo
HI Laszlo,
Is it possible to become a contributor to the project?
You need to create a fork first, commit/push your changes and open a PR then. Here are the guidelines: https://github.com/MarcDiethelm/contributing/blob/master/README.md (which I'll be copying here sometime soon; marking this issue as documentation to not forget).
As a side note, why you do use KeyValuePair instead of tuples (e.g (key, value)
)? Not suggesting that you should, just curious.
Hi Vladimir, allright, i would read the documentation and follow the steps. To answer your question: Call me old school. Jokes aside!
I prefer to use a Dictionary<K,V>
, which is an IEnumerable<KeyValuePair<K, V>>
, than a List<Tuple<T1, T2>>
. On the one hand because of the uniqueness of the keys of a dictionary, on the other hand I have to do a lot in my projects with large InMemory data containers that are read / written to in parallel and here, i prefer the ConcurrentDictionary<K,V>
(which holds a KeyValuePair).
You will find the pull-Request to this enhancement here https://github.com/vkhorikov/CSharpFunctionalExtensions/pull/300
Regards, Laszlo
Sounds good! I'm merging the PR, it will be published shortly as v2.17.0