Last active
May 1, 2016 20:56
-
-
Save timyates/8e7d43028db42aabe4d434e457ec9442 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 fizzbuzz; | |
import javaslang.collection.Stream; | |
import javaslang.control.Option; | |
import static javaslang.control.Option.none; | |
import static javaslang.control.Option.some; | |
public class SlangFizzBuzz { | |
public static void main(String[] args) { | |
Stream<String> nums = Stream.from(1).map(Object::toString); | |
Stream<Option<String>> fizz = Stream.<Option<String>>of(none(), none(), some("Fizz")).cycle(); | |
Stream<Option<String>> buzz = Stream.<Option<String>>of(none(), none(), none(), none(), some("Buzz")).cycle(); | |
Stream<Option<String>> pattern = fizz.zip(buzz).map(t -> t._1.flatMap(s -> t._2.map(s2 -> s + s2).orElse(t._1)).orElse(t._2)); | |
Stream<String> fizzbuzz = pattern.zip(nums).map(t -> t._1.getOrElse(t._2)); | |
fizzbuzz.take(15).forEach(System.out::println); | |
} | |
} |
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 fizzbuzz; | |
import javaslang.Tuple2; | |
import javaslang.collection.Stream; | |
import javaslang.control.Option; | |
import java.util.function.BinaryOperator; | |
import static javaslang.control.Option.none; | |
import static javaslang.control.Option.some; | |
public class SlangFizzBuzzWithHelper { | |
public static void main(String[] args) { | |
Stream<String> nums = Stream.from(1).map(Object::toString); | |
Stream<Option<String>> fizz = Stream.<Option<String>>of(none(), none(), some("Fizz")).cycle(); | |
Stream<Option<String>> buzz = Stream.<Option<String>>of(none(), none(), none(), none(), some("Buzz")).cycle(); | |
Stream<Option<String>> pattern = fizz.zip(buzz).map(t -> eitherNeitherOrBoth(t, (a, b) -> a + b)); | |
Stream<String> fizzbuzz = pattern.zip(nums).map(t -> t._1.getOrElse(t._2)); | |
fizzbuzz.take(15).forEach(System.out::println); | |
} | |
private static <T> Option<T> eitherNeitherOrBoth(Tuple2<Option<T>,Option<T>> tuple, BinaryOperator<T> combiner) { | |
return tuple._1.flatMap(left -> tuple._2.map(right -> combiner.apply(left, right)).orElse(tuple._1)).orElse(tuple._2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment