Last active
November 28, 2015 20:29
-
-
Save mmhelloworld/eac189d52cd1e2a91ad5 to your computer and use it in GitHub Desktop.
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
package helloworld; | |
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.Iterator; | |
import java.util.List; | |
import static java.lang.String.format; | |
import static java.lang.System.out; | |
import static java.util.Arrays.asList; | |
import static java.util.function.Function.identity; | |
import static java.util.stream.Collectors.toList; | |
/** | |
* See https://dierk.gitbooks.io/fregegoodness/content/src/docs/asciidoc/higher-ranked.html | |
*/ | |
public class Main { | |
public static void main(String[] args) { | |
out.println(fzip(Main::mapIdentity, asList("one", "two", "three"), asList(1, 2, 3))); | |
out.println(fzip(Main::reverse, asList("one", "two", "three"), asList(1, 2, 3))); | |
} | |
public static <A, B> List<Tuple<A, B>> fzip(MyFunction f, List<A> xs, List<B> ys) { | |
return zip(f.apply(xs), f.apply(ys)); | |
} | |
public static <A, B> List<Tuple<A, B>> zip(List<A> xs, List<B> ys) { | |
List<Tuple<A, B>> res = new ArrayList<>(); | |
Iterator<B> ysItr = ys.iterator(); | |
for (A x: xs) { | |
if (ysItr.hasNext()) { | |
final B y = ysItr.next(); | |
res.add(new Tuple<>(x, y)); | |
} else { | |
return res; | |
} | |
} | |
return res; | |
} | |
public static <A> List<A> mapIdentity(List<A> xs) { | |
return xs.stream().map(identity()).collect(toList()); | |
} | |
public static <A> List<A> reverse(List<A> xs) { | |
List<A> ys = new ArrayList<>(xs); | |
Collections.reverse(ys); | |
return ys; | |
} | |
@FunctionalInterface | |
public interface MyFunction { | |
<A> List<A> apply(List<A> xs); | |
} | |
public static class Tuple<A, B> { | |
public final A first; | |
public final B second; | |
public Tuple(A first, B second) { | |
this.first = first; | |
this.second = second; | |
} | |
@Override | |
public String toString() { | |
return format("(%s, %s)", first, second); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment