Skip to content

Instantly share code, notes, and snippets.

@danieldietrich
Last active May 3, 2016 19:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danieldietrich/bda57e236cbe60f17469e867e470c857 to your computer and use it in GitHub Desktop.
Save danieldietrich/bda57e236cbe60f17469e867e470c857 to your computer and use it in GitHub Desktop.
import javaslang.collection.Stream;
import javaslang.control.Option;
import java.io.Serializable;
import static javaslang.collection.Stream.*;
import static javaslang.control.Option.*;
/**
* In Javaslang 2.0.2 zipWith is missing. I temporarily added it to Stream:
*
* <pre><code>
* default <U, R> Stream<R> zipWith(BiFunction<? super T, ? super U, ? extends R> combiner, Iterable<? extends U> iterable) {
* return zip(iterable).map(t -> combiner.apply(t._1, t._2));
* }
* </code></pre>
*/
public class FizzBuzz {
public static void main(String[] args) {
Stream<Integer> nums = from(1);
Stream<Option<String>> fizzes = Stream.<Option<String>> of(none(), none(), some("fizz")).cycle();
Stream<Option<String>> buzzes = Stream.<Option<String>> of(none(), none(), none(), none(), some("buzz")).cycle();
Stream<Option<String>> pattern = fizzes.zipWith(FizzBuzz::combine, buzzes);
Stream<? extends Serializable> fizzbuzzes = nums.zipWith(FizzBuzz::fromMaybe, pattern);
fizzbuzzes.take(15).stdout();
}
// currently I have no solution for making String monoidic and inducing the combine operation '+'
static Option<String> combine(Option<String> o1, Option<String> o2) {
return o1.flatMap(s1 -> o2.map(s2 -> s1 + s2).orElse(o1)).orElse(o2);
}
@SuppressWarnings("unchecked")
static <R, T extends R, U extends R> R fromMaybe(T that, Option<U> option) {
return ((Option<R>) option).getOrElse((R) that);
}
}
import static javaslang.collection.Stream.*;
import static javaslang.control.Option.*;
/**
* Hopefully we get var and val with reasonable type inference in Java 9.
*
* Moving the helper methods to Monoid and Option and solving the combine-problem described above
* will lead to this solution.
*/
public class FizzBuzz {
public static void main(String[] args) {
val nums = from(1);
val fizzes = of(none(), none(), some("fizz")).cycle();
val buzzes = of(none(), none(), none(), none(), some("buzz")).cycle();
val pattern = fizzes.zipWith(Monoid::combine, buzzes);
val fizzbuzzes = nums.zipWith(Option::fromOption, pattern);
fizzbuzzes.take(15).stdout();
}
}
Copy link

ghost commented May 3, 2016

Woa, I see somebody using the Java "import static" for the first time here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment