Skip to content

Commit

Permalink
Distinct changes
Browse files Browse the repository at this point in the history
  • Loading branch information
louthy committed Mar 6, 2017
1 parent d6971e7 commit daa5a10
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
23 changes: 20 additions & 3 deletions LanguageExt.Core/DataTypes/List/Lst.Module.cs
Original file line number Diff line number Diff line change
Expand Up @@ -778,6 +778,16 @@ public static IEnumerable<T> distinct<T>(IEnumerable<T> list) =>
public static IEnumerable<T> distinct<EQ, T>(IEnumerable<T> list) where EQ : struct, Eq<T> =>
list.Distinct(new EqCompare<T>((x, y) => default(EQ).Equals(x, y)));

/// <summary>
/// Return a new enumerable with all duplicate values removed
/// </summary>
/// <typeparam name="T">Enumerable item type</typeparam>
/// <param name="list">Enumerable</param>
/// <returns>A new enumerable with all duplicate values removed</returns>
[Pure]
public static IEnumerable<T> distinct<T, K>(IEnumerable<T> list, Func<T, K> keySelector, Option<Func<K, K, bool>> compare = default(Option<Func<K, K, bool>>)) =>
list.Distinct(new EqCompare<T>((a, b) => compare.IfNone(EqualityComparer<K>.Default.Equals)(keySelector(a), keySelector(b)), a => keySelector(a)?.GetHashCode() ?? 0));

/// <summary>
/// Returns a new enumerable with the first 'count' items from the enumerable provided
/// </summary>
Expand Down Expand Up @@ -1148,12 +1158,19 @@ public static Tuple<IEnumerable<T>, IEnumerable<T>> span<T>(IEnumerable<T> self,
class EqCompare<T> : IEqualityComparer<T>
{
readonly Func<T, T, bool> compare;
readonly Option<Func<T, int>> hashCode = None;

public EqCompare(Func<T, T, bool> compare)
{
this.compare = compare;
}

public EqCompare(Func<T, T, bool> compare, Func<T, int> hashCode)
{
this.compare = compare;
this.hashCode = hashCode;
}

[Pure]
public bool Equals(T x, T y) =>
isnull(x) && isnull(y)
Expand All @@ -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);
}
}
1 change: 0 additions & 1 deletion LanguageExt.Tests/HashSetTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using LanguageExt;
using LanguageExt.Trans;
using static LanguageExt.Prelude;
using static LanguageExt.HashSet;
using Xunit;
Expand Down

0 comments on commit daa5a10

Please sign in to comment.