/*
 * Copyright (C) 2016 Reece H. Dunn
 *
 * 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 uk.co.reecedunn.intellij.plugin.xquery.functional;

import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Predicate;

public interface Foldable<A> {
    <V> V fold(BiFunction<A, V, V> foldOver, V initialValue);

    default <V> V foldIf(Predicate<A> matcher, BiFunction<A, V, V> foldOver, V initialValue) {
        return fold((a, b) -> {
            if (matcher.test(a)) {
                return foldOver.apply(a, b);
            }
            return b;
        }, initialValue);
    }

    default <V> V foldIf(Class c, BiFunction<A, V, V> foldOver, V initialValue) {
        return foldIf(c::isInstance, foldOver, initialValue);
    }

    default int count() {
        return fold((a, value) -> value + 1, 0);
    }

    default int countOf(Predicate<A> matcher) {
        return foldIf(matcher, (a, value) -> value + 1, 0);
    }

    default int countOf(Class c) {
        return foldIf(c::isInstance, (a, value) -> value + 1, 0);
    }

    default List<A> toList() {
        return fold((a, c) -> { c.add(a); return c; }, new ArrayList<A>());
    }
}

@@ -871,33 +871,81 @@
 alue);%0A%0A    
-default %3C
+@SuppressWarnings(%22unchecked%22)%0A    default %3CB extends A, 
 V%3E V foldIf(
@@ -946,33 +946,33 @@
 oldIf(Predicate%3C
-A
+B
 %3E matcher, BiFun
@@ -969,33 +969,33 @@
 her, BiFunction%3C
-A
+B
 , V, V%3E foldOver
@@ -1075,16 +1075,19 @@
 er.test(
+(B)
 a)) %7B%0A  
@@ -1122,16 +1122,19 @@
 r.apply(
+(B)
 a, b);%0A 
@@ -1769,11 +1769,276 @@
 );%0A    %7D
+%0A%0A    default %3CB extends A%3E List%3CB%3E toListOf(Predicate%3CB%3E matcher) %7B%0A        return foldIf(matcher, (a, c) -%3E %7B c.add(a); return c; %7D, new ArrayList%3CB%3E());%0A    %7D%0A%0A    default %3CB extends A%3E List%3CB%3E toListOf(Class%3CB%3E c) %7B%0A        return toListOf(c::isInstance);%0A    %7D
 %0A%7D%0A

Allow Foldable::foldIf to operate over derived types and use this to implement a predicated version of toList.