From daa5a10028e9637b5e55ff103ea31330361407fc Mon Sep 17 00:00:00 2001
From: Paul Louth
Date: Mon, 6 Mar 2017 04:45:24 +0000
Subject: [PATCH] Distinct changes
---
LanguageExt.Core/DataTypes/List/Lst.Module.cs | 23 ++++++++++++++++---
LanguageExt.Tests/HashSetTests.cs | 1 -
2 files changed, 20 insertions(+), 4 deletions(-)
diff --git a/LanguageExt.Core/DataTypes/List/Lst.Module.cs b/LanguageExt.Core/DataTypes/List/Lst.Module.cs
index b44dc417c..144acfc77 100644
--- a/LanguageExt.Core/DataTypes/List/Lst.Module.cs
+++ b/LanguageExt.Core/DataTypes/List/Lst.Module.cs
@@ -778,6 +778,16 @@ public static IEnumerable distinct(IEnumerable list) =>
public static IEnumerable distinct(IEnumerable list) where EQ : struct, Eq =>
list.Distinct(new EqCompare((x, y) => default(EQ).Equals(x, y)));
+ ///
+ /// Return a new enumerable with all duplicate values removed
+ ///
+ /// Enumerable item type
+ /// Enumerable
+ /// A new enumerable with all duplicate values removed
+ [Pure]
+ public static IEnumerable distinct(IEnumerable list, Func keySelector, Option> compare = default(Option>)) =>
+ list.Distinct(new EqCompare((a, b) => compare.IfNone(EqualityComparer.Default.Equals)(keySelector(a), keySelector(b)), a => keySelector(a)?.GetHashCode() ?? 0));
+
///
/// Returns a new enumerable with the first 'count' items from the enumerable provided
///
@@ -1148,12 +1158,19 @@ public static Tuple, IEnumerable> span(IEnumerable self,
class EqCompare : IEqualityComparer
{
readonly Func compare;
+ readonly Option> hashCode = None;
public EqCompare(Func compare)
{
this.compare = compare;
}
+ public EqCompare(Func compare, Func hashCode)
+ {
+ this.compare = compare;
+ this.hashCode = hashCode;
+ }
+
[Pure]
public bool Equals(T x, T y) =>
isnull(x) && isnull(y)
@@ -1164,8 +1181,8 @@ public bool Equals(T x, T y) =>
[Pure]
public int GetHashCode(T obj) =>
- isnull(obj)
- ? 0
- : obj.GetHashCode();
+ hashCode.Match(
+ f => isnull(obj) ? 0 : f(obj),
+ () => 0);
}
}
\ No newline at end of file
diff --git a/LanguageExt.Tests/HashSetTests.cs b/LanguageExt.Tests/HashSetTests.cs
index 7765c864e..7c256d379 100644
--- a/LanguageExt.Tests/HashSetTests.cs
+++ b/LanguageExt.Tests/HashSetTests.cs
@@ -1,5 +1,4 @@
using LanguageExt;
-using LanguageExt.Trans;
using static LanguageExt.Prelude;
using static LanguageExt.HashSet;
using Xunit;