Created
July 26, 2019 03:02
-
-
Save ayago/4aab435e3fe79b91d72bdc0fa933af3b to your computer and use it in GitHub Desktop.
Folding in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.math.BigDecimal; | |
import java.util.ArrayList; | |
import java.util.Collection; | |
import java.util.Collections; | |
import java.util.List; | |
import static java.lang.String.format; | |
import static java.util.Arrays.asList; | |
class SampleFolding { | |
public static void main(String[] args) { | |
Fx2<BigDecimal, String, BigDecimal> addAsBigDecimal = (d, s) -> d.add(new BigDecimal(s)); | |
Collection<String> stringDecimals = asList("1.00", "2.00", "3.00"); | |
BigDecimal bigDecimal = Folding.foldLeft(addAsBigDecimal, BigDecimal.ZERO, stringDecimals); | |
System.out.println(format("Should be 6.00: %s", bigDecimal)); | |
Fx2<String, BigDecimal, String> appender = (d, s) -> d.concat(s.toString()); | |
Collection<BigDecimal> decimals = asList( | |
new BigDecimal("1.00"), new BigDecimal("2.00"), new BigDecimal("3.00")); | |
String stringRep = Folding.foldRight(appender, "", decimals); | |
System.out.println(format("Should be 3.002.001.00: %s", stringRep)); | |
} | |
/** | |
* Function with arity of 2 | |
* @param <I1> type of first input | |
* @param <I2> type of second input | |
* @param <O> type of output | |
*/ | |
@FunctionalInterface | |
public interface Fx2<I1, I2, O> { | |
/** | |
* Execute this function | |
* @param inputOne first input | |
* @param inputTwo second input | |
* @return output of this function | |
*/ | |
O apply(I1 inputOne, I2 inputTwo); | |
} | |
public static class Folding { | |
//left associative or start from left | |
public static <A, B> A foldLeft(final Fx2<A, ? super B, A> f, final A initial, final Collection<B> bc){ | |
return bc.stream().reduce(initial, f::apply, (c, d) -> d); | |
} | |
//right associative or start from right | |
public static <A, B> A foldRight(final Fx2<A, B, A> f, final A initial, final Collection<B> bc){ | |
if(bc.size() == 0) { | |
return initial; | |
} | |
List<B> reversed = new ArrayList<>(bc); | |
Collections.reverse(reversed); | |
return foldLeft(f, initial, reversed); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment