Skip to content

Commit

Permalink
Simplify Functions
Browse files Browse the repository at this point in the history
  • Loading branch information
Glavo committed Jan 5, 2025
1 parent 0982dd1 commit dfc162f
Showing 1 changed file with 8 additions and 30 deletions.
38 changes: 8 additions & 30 deletions kala-base/src/main/java/kala/function/Functions.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@
package kala.function;

import kala.annotations.StaticClass;
import kala.internal.InternalIdentifyObject;
import kala.tuple.Tuple;
import kala.tuple.Tuple2;
import kala.tuple.Tuple3;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;

Expand Down Expand Up @@ -85,14 +85,7 @@ public static <T, R> Function<T, R> of(Function<? super T, ? extends R> function
return (t, u) -> function.apply(t).apply(u);
}

private enum NullHole {
INSTANCE;

@Override
public String toString() {
return "null";
}
}
private static final InternalIdentifyObject NULL_HOLE = new InternalIdentifyObject();

private enum Identity implements Function<Object, Object> {
INSTANCE;
Expand All @@ -118,37 +111,22 @@ public String toString() {
}
}

private static final class MemoizedFunction<T, R> implements Function<T, R>, Memoized, Serializable {
private static final long serialVersionUID = -904511663627169337L;

final @NotNull Function<? super T, ? extends R> function;
final @NotNull Map<T, Object> cache;
final boolean sync;

MemoizedFunction(@NotNull Function<? super T, ? extends R> function, @NotNull Map<T, Object> cache, boolean sync) {
this.function = function;
this.cache = cache;
this.sync = sync;
}

private record MemoizedFunction<T, R>(@NotNull Function<? super T, ? extends R> function,
@NotNull Map<T, Object> cache,
boolean sync) implements Function<T, R>, Memoized, Serializable {
@Override
public R apply(T t) {
Object res = cache.computeIfAbsent(t, key -> {
R v = function.apply(key);
return v != null ? v : NullHole.INSTANCE;
return v != null ? v : NULL_HOLE;
});

return res != NullHole.INSTANCE ? (R) res : null;
return res != NULL_HOLE ? (R) res : null;
}

@Override
public String toString() {
return "MemoizedFunction[" +
"function=" + function +
", cache=" + cache +
']';
return "MemoizedFunction[function=%s, cache=%s]".formatted(function, cache);
}


}
}

0 comments on commit dfc162f

Please sign in to comment.