/*
 * 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);

    @SuppressWarnings("unchecked")
    default <B extends A, V> V foldIf(Predicate<B> matcher, BiFunction<B, V, V> foldOver, V initialValue) {
        return fold((a, b) -> {
            if (matcher.test((B)a)) {
                return foldOver.apply((B)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>());
    }

    default <B extends A> List<B> toListOf(Predicate<B> matcher) {
        return foldIf(matcher, (a, c) -> { c.add(a); return c; }, new ArrayList<B>());
    }

    default <B extends A> List<B> toListOf(Class<B> c) {
        return toListOf(c::isInstance);
    }
}

@@ -946,33 +946,33 @@
 oldIf(Predicate%3C
-B
+A
 %3E matcher, BiFun
@@ -1075,19 +1075,16 @@
 er.test(
-(B)
 a)) %7B%0A  
@@ -1211,16 +1211,29 @@
 efault %3C
+B extends A, 
 V%3E V fol
@@ -1237,16 +1237,19 @@
 fold
-I
+O
 f(Class
+%3CB%3E
  c, 
@@ -1251,33 +1251,33 @@
 %3E c, BiFunction%3C
-A
+B
 , V, V%3E foldOver
@@ -1468,17 +1468,17 @@
 nt count
-O
+I
 f(Predic
@@ -1799,37 +1799,23 @@
 ault
- %3CB extends A%3E
  List%3C
-B
+A
 %3E toList
 Of(P
@@ -1810,17 +1810,17 @@
 %3E toList
-O
+I
 f(Predic
@@ -1823,17 +1823,17 @@
 edicate%3C
-B
+A
 %3E matche
@@ -1917,17 +1917,16 @@
 rayList%3C
-B
 %3E());%0A  
@@ -2006,30 +2006,70 @@
 urn 
-toListOf(c::isInstance
+foldOf(c, (a, l) -%3E %7B l.add(a); return l; %7D, new ArrayList%3C%3E()
 );%0A 

Improve the extended methods in Foldable<A>.