All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.basking2.sdsai.itrex.functions.functional.ComposeFunction Maven / Gradle / Ivy

There is a newer version: 1.1.23
Show newest version
package com.github.basking2.sdsai.itrex.functions.functional;

import com.github.basking2.sdsai.itrex.EvaluationContext;
import com.github.basking2.sdsai.itrex.SExprRuntimeException;
import com.github.basking2.sdsai.itrex.functions.FunctionInterface;
import com.github.basking2.sdsai.itrex.iterators.Iterators;

import java.util.Iterator;

/**
 * Given a list of functions, f, g, h, compose them such that they are called in
 * the order f(g(h)).
 */
public class ComposeFunction implements FunctionInterface> {

    @Override
    @SuppressWarnings("unchecked")
    public FunctionInterface apply(Iterator iterator, final EvaluationContext evaluationContext) {

        FunctionInterface f = null;

        while (iterator.hasNext()) {
            final Object o = iterator.next();
            if (o instanceof FunctionInterface) {
                if (f == null) {
                    f = (FunctionInterface) o;
                }
                else {

                    final FunctionInterface finalF = f;
                    final FunctionInterface finalO = (FunctionInterface) o;

                    f = (in, ctx) ->  {
                        final Object fOutput = Iterators.wrap(finalO.apply(in, ctx));
                        return finalF.apply((Iterator)fOutput, ctx);
                    };
                }
            }
            else {
                throw new SExprRuntimeException("Argument to compose must be a function: "+o.toString());
            }
        }

        return f;
    }
}