A better Dictionary #29
arialdomartini
started this conversation in
Ideas
Replies: 1 comment 7 replies
-
|
Mi viene in mente che l'approccio più naturale potrebbe essere quella di usare un Un approccio non rigorosamente funzionale (non ha strutture mutabili) potrebbe essere questo: static class DictionaryExtensions
{
internal static TValue Get<TKey, TValue>(
this Dictionary<TKey, TValue> dictionary,
TKey key,
Func<TValue> fallback) =>
dictionary.ContainsKey(key) ?
dictionary[key] :
fallback();
}
public class DictionaryTest
{
[Fact]
void fallback()
{
var dictionary = new Dictionary<int, string>
{
[1] = "foo",
[2] = "bar"
};
dictionary.Get(1, () => "fallback")
.Should().Be("foo");
dictionary.Get(-99, () => "fallback")
.Should().Be("fallback");
}
}Come valore di fallback uso una function, in modo che la valutazione sia lazy. Si potrebbe anche pensare a un static class DictionaryUpdateExtensions
{
internal static TValue GetUpdate<TKey, TValue>(
this Dictionary<TKey, TValue> dictionary,
TKey key,
Func<TValue> fallback)
{
if (!dictionary.ContainsKey(key))
dictionary.Add(key, fallback());
return dictionary[key];
}
}
public class DictionaryUpdateTest
{
[Fact]
void uses_fallback()
{
var dictionary = new Dictionary<int, string>
{
[1] = "foo",
[2] = "bar"
};
dictionary.GetUpdate(1, () => "fallback").Should().Be("foo");
dictionary.GetUpdate(-99, () => "fallback").Should().Be("fallback");
}
[Fact]
void stores_fallback()
{
var dictionary = new Dictionary<int, string>
{
[1] = "foo",
[2] = "bar"
};
dictionary.ContainsKey(-99).Should().Be(false);
dictionary.GetUpdate(-99, () => "fallback").Should().Be("fallback");
dictionary.ContainsKey(-99).Should().Be(true);
}
}Sono sicuro a voi verranno in mente implementazioni più fantasiose e furbe. |
Beta Was this translation helpful? Give feedback.
7 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
@aironangel ha proposto un tema: un approccio funzionale per la gestione dei dizionari, in particolare per la gestione delle chiavi inesistenti.
Usiamo questa discussion per raccogliere un po' di idee?
Beta Was this translation helpful? Give feedback.
All reactions