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

com.github.basking2.sdsai.itrex.functions.functional.MapFunction 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.AbstractFunction1;
import com.github.basking2.sdsai.itrex.functions.FunctionInterface;
import com.github.basking2.sdsai.itrex.iterators.MappingIterator;

import java.util.ArrayList;
import java.util.Iterator;

import static com.github.basking2.sdsai.itrex.iterators.Iterators.toIterator;
import static com.github.basking2.sdsai.itrex.iterators.Iterators.wrap;

/**
 * Map a function across all subsequent arguments.
 */
public class MapFunction extends AbstractFunction1, Iterator> {
    @Override
    protected Iterator applyImpl(final FunctionInterface function, final Iterator rest, final EvaluationContext evaluationContext) {
        if (!rest.hasNext()) {
            throw new SExprRuntimeException("Map function requires a second argument.");
        }
        final Object iteratorObject = rest.next();

        final Iterator returnIterator = toIterator(iteratorObject);
        if (returnIterator == null) {
            throw new SExprRuntimeException("Second argument must be an iterator.");
        }

        return new MappingIterator(returnIterator, o -> function.apply(wrap(o), evaluationContext));
    }
}