Last active
August 29, 2015 14:07
-
-
Save havenwood/c5c5b48bd96b77bea53d to your computer and use it in GitHub Desktop.
Transducer FizzBuzz
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
require 'transducers' | |
T = Transducers | |
fizzducer = T.compose T.map { |n| n % 3 == 0 && n % 5 == 0 && 'FizzBuzz' || n }, | |
T.map { |n| n % 3 == 0 && 'Fizz' || n }, | |
T.map { |n| n % 5 == 0 && 'Buzz' || n }, | |
T.map(:to_s) | |
T.transduce fizzducer, :puts, STDOUT, 1.upto(5) | |
#>> 1 | |
#>> 2 | |
#>> Fizz | |
#>> 4 | |
#>> Buzz | |
T.transduce fizzducer, :<<, '', [1, 2, 3, 4, 5] | |
#=> "12Fizz4Buzz" | |
T.transduce T.compose(fizzducer, T.map { |n| n << "\n" }), :<<, '', 1..5 | |
#=> "1\n2\nFizz\n4\nBuzz\n" | |
T.transduce T.compose(fizzducer, T.map(:to_i)), :+, 0, 1..5 | |
#=> 7 | |
T.transduce fizzducer, :<<, [], 1.upto(5) | |
#=> ["1", "2", "Fizz", "4", "Buzz"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment