Skip to content

Commit

Permalink
semigroups minby and maxby
Browse files Browse the repository at this point in the history
  • Loading branch information
jyrimatti committed Jul 21, 2023
1 parent b97f5a4 commit d943568
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>fi.solita.utils</groupId>
<artifactId>functional-utils</artifactId>
<version>0.12.35</version>
<version>0.12.36</version>
<build>
<resources>
<resource>
Expand Down
34 changes: 33 additions & 1 deletion src/main/java/fi/solita/utils/functional/SemiGroups.java
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,14 @@ public static final <T extends Comparable<T>> SemiGroup<T> min() {
return (SemiGroup<T>) min;
}

public static final <T> SemiGroup<T> maxBy(Comparator<? super T> comparator) {
return new MaxBy<T>(comparator);
}

public static final <T> SemiGroup<T> minBy(Comparator<? super T> comparator) {
return new MinBy<T>(comparator);
}

public static final <T> SemiGroup<Set<T>> setUnion() {
return Monoids.setUnion();
}
Expand Down Expand Up @@ -233,7 +241,31 @@ static final class Min<T extends Comparable<T>> extends Function2<T,T,T> impleme
public final T apply(T t1, T t2) {
return t1.compareTo(t2) > 0 ? t2 : t1;
}
}
}

static final class MaxBy<T> extends Function2<T,T,T> implements SemiGroup<T> {
private final Comparator<? super T> comparator;
public MaxBy(Comparator<? super T> comparator) {
this.comparator = comparator;
}

@Override
public final T apply(T t1, T t2) {
return comparator.compare(t1, t2) < 0 ? t2 : t1;
}
}

static final class MinBy<T> extends Function2<T,T,T> implements SemiGroup<T> {
private final Comparator<? super T> comparator;
public MinBy(Comparator<? super T> comparator) {
this.comparator = comparator;
}

@Override
public final T apply(T t1, T t2) {
return comparator.compare(t1, t2) > 0 ? t2 : t1;
}
}

static class Endo<T> extends Function2<Apply<T,T>,Apply<T,T>,Apply<T,T>> implements SemiGroup<Apply<T, T>> {
@Override
Expand Down

0 comments on commit d943568

Please sign in to comment.