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

io.parsingdata.metal.expression.value.Elvis Maven / Gradle / Ivy

There is a newer version: 10.0.0
Show newest version
/*
 * Copyright 2013-2016 Netherlands Forensic Institute
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.parsingdata.metal.expression.value;

import static io.parsingdata.metal.Util.checkNotNull;

import io.parsingdata.metal.data.Environment;
import io.parsingdata.metal.data.ImmutableList;
import io.parsingdata.metal.encoding.Encoding;

/**
 * A {@link ValueExpression} that implements the Elvis operator:
 * 
?:
. *

* An Elvis expression has two operands: left and * right (both {@link ValueExpression}s). Both operands are * evaluated. The return value is a list with the size of the longest list * returned by the two evaluations. At each index, the value at that index in * the result returned by evaluating left is placed, except if it * does not exist or is {@link OptionalValue#empty()}, in which case the value * at that index in the result returned by evaluating right is placed there. */ public class Elvis implements ValueExpression { public final ValueExpression left; public final ValueExpression right; public Elvis(final ValueExpression left, final ValueExpression right) { this.left = checkNotNull(left, "left"); this.right = checkNotNull(right, "right"); } @Override public ImmutableList eval(final Environment environment, final Encoding encoding) { return eval(left.eval(environment, encoding), right.eval(environment, encoding)); } private ImmutableList eval(final ImmutableList leftValues, final ImmutableList rightValues) { if (leftValues.isEmpty()) { return rightValues; } if (rightValues.isEmpty()) { return leftValues; } return eval(leftValues.tail, rightValues.tail).add(leftValues.head.isPresent() ? leftValues.head : rightValues.head); } @Override public String toString() { return getClass().getSimpleName() + "(" + left + "," + right + ")"; } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy