io.rouz.flo.BuilderUtils Maven / Gradle / Ivy
package io.rouz.flo;
import static java.util.stream.Collectors.toList;
import io.rouz.flo.TaskContext.Value;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
/**
* Internal utility functions for the {@link TaskBuilder} api implementation
*/
class BuilderUtils {
private BuilderUtils() {
}
static ChainingEval leafEvalFn(EvalClosure>> fClosure) {
return new ChainingEval<>(fClosure);
}
static EvalClosure gated(TaskId taskId, Fn code) {
return tc -> tc.invokeProcessFn(taskId, () -> tc.value(code));
}
static EvalClosure gatedVal(
TaskId taskId,
Fn1> code) {
return tc -> tc.invokeProcessFn(taskId, () -> code.apply(tc));
}
/**
* Converts an array of {@link Fn}s of {@link Task}s to a {@link Fn} of a list of
* those tasks {@link Task}s.
*
* It will only evaluate the functions (through calling {@link Fn#get()})
* when the returned function is invoked. Thus it retains laziness.
*
* @param tasks An array of lazy evaluated tasks
* @return A function of a list of lazily evaluated tasks
*/
@SafeVarargs
static Fn>> lazyList(Fn extends Task>>... tasks) {
return () -> Stream.of(tasks)
.map(Fn::get)
.collect(toList());
}
@SafeVarargs
static Fn> lazyFlatten(Fn extends List extends T>>... lists) {
return () -> Stream.of(lists)
.map(Fn::get)
.flatMap(List::stream)
.collect(toList());
}
static List appendToList(List list, T t) {
final List newList = new ArrayList<>(list);
newList.add(t);
return newList;
}
static final class ChainingEval implements Serializable {
private final EvalClosure>> fClosure;
ChainingEval(EvalClosure>> fClosure) {
this.fClosure = fClosure;
}
EvalClosure enclose(F f) {
return taskContext -> fClosure.eval(taskContext).flatMap(ff -> ff.apply(f));
}
ChainingEval chain(EvalClosure> mapClosure) {
EvalClosure>> continuation = tc -> {
Value> gv = mapClosure.eval(tc);
Value>> fv = fClosure.eval(tc);
return Values.mapBoth(tc, gv, fv, (gc, fc) -> g -> fc.apply(gc.apply(g)));
};
return new ChainingEval<>(continuation);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy