Skip to content

Commit

Permalink
Added FixpointIterator to utils (function package)
Browse files Browse the repository at this point in the history
Aklakan committed Sep 8, 2023
1 parent d854861 commit c6cb88e
Showing 1 changed file with 45 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package org.aksw.commons.util.function;

import java.util.Objects;
import java.util.function.Function;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FixpointIteration {

private static Logger logger = LoggerFactory.getLogger(FixpointIteration.class);

public static <T> Function<T, T> createClosure(Function<? super T, ? extends T> transform) {
return op -> apply(op, transform);
}

public static <T> T apply(T op, Function<? super T, ? extends T> transform) {
T current;
do {
current = op;
op = transform.apply(current);
} while(!current.equals(op));

return current;
}

public static <T> T apply(int max, T init, Function<? super T, ? extends T> fn) {
T result = init;

int i = 0;
for(; i < max; ++i) {
T tmp = fn.apply(result);
if(Objects.equals(tmp, result)) {
break;
}
result = tmp;
}

if(i >= max) {
logger.warn("Fixpoint iteration reached iteration threshold");
}

return result;
}
}

0 comments on commit c6cb88e

Please sign in to comment.