alan dipert RSS

github / twitter / resume / email
Aug
26th
Wed
permalink

FizzBuzz in Scala and Clojure

The problem:

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

Scala 2.7.5:

(1 to 100) map { x =>   
  (x % 3, x % 5) match {  
    case (0,0) => "FizzBuzz"
    case (0,_) => "Fizz"    
    case (_,0) => "Buzz"    
    case _ => x toString    
  }
} foreach println

Clojure with David Nolen’s match library:

(use '[match.core :only (match)])

(doseq [n (range 1 101)]
  (println (match [(mod n 3) (mod n 5)]
                  [0 0] "FizzBuzz"
                  [0 _] "Fizz"
                  [_ 0] "Buzz"
                  :else n)))

It intrigues that a core language construct in one language can be delivered as a library in another.

Comments (View)
blog comments powered by Disqus