3 ms·
That's a slick way to remove the conditionals indeed. Inspired by it, here's a Scala version (checked with v2.11): object Fizzbuzz { val fizzes = Li
by AdieuToLogic 10y ago
That's a slick way to remove the conditionals indeed. Inspired by it, here's a Scala version (checked with v2.11):
object Fizzbuzz
{
val fizzes = List (None, None, Some ("Fizz")).toStream;
val buzzes = List (None, None, None, None, Some ("Buzz")).toStream;
val reducer : (Option[String], Option[String]) => Option[String] =
(a, b) => Option ((a ++ b).mkString).filterNot (_.isEmpty);
def apply (amount : Int) : Seq[String] =
Stream.continually (fizzes)
.flatten
.zip (Stream.continually (buzzes).flatten)
.map (reducer.tupled)
.zipWithIndex
.map {
case (s, n) => s.getOrElse ((n + 1).toString);
}
.take (amount);
}
Fizzbuzz (100).foreach (println)
- viebel 10y agoIt's amazing how scala syntax is verbose - not to say ugly!
- AdieuToLogic 10y agoI was being intentionally verbose so that readers not familiar with Scala or the collections types/methods used would have an easier time following it. I also was avoiding use of pattern matching as they are cousins to conditionals IMHO. However, below is another version which employs idioms more commonly found: object Fizzbuzz { val fizzes = None :: None :: Some ("Fizz") :: Nil; val buzzes = None :: None :: None :: None :: Some ("Buzz") :: Nil; def apply (amount : Int) : TraversableOnce[String] = { val alternates = Stream.continually (fizzes).flatten .zip (Stream.continually (buzzes).flatten) .take (amount) .toArray; 0.until (amount).map { n => alternates (n) match { case (Some (f), Some (b)) => f + b; case (Some (f), None) => f; case (None, Some (b)) => b; case _ => (n + 1).toString } } } } Fizzbuzz (100).foreach (println);
- viebel 10y agoOh! I see. It's much more concise and clean now. But still I prefer the clojure version using pattern matching over the scala one: http://blog.klipse.tech/clojure/2016/10/25/core-match.html#fizzbuzz http://blog.klipse.tech/clojure/2016/10/25/core-match.html#f...
- AdieuToLogic 10y agoGotcha. Then here's a translation into Scala from the link you provided which I believe maintains the spirit of the clojure version: object Fizzbuzz { def apply (amount : Int) : TraversableOnce[String] = 1.to (amount).map { n => (n % 3, n % 5) match { case (0, 0) => "FizzBuzz"; case (0, _) => "Fizz"; case (_, 0) => "Buzz"; case _ => n.toString } } } Fizzbuzz (100).foreach (println); EDIT: When I said "Gotcha", I meant that as in "understood" and not in an adversarial manner. Quite the opposite, actually, as this is a respectful thread which I believe both parties have enjoyed.