Skip to content

Instantly share code, notes, and snippets.

@ljsc
Last active August 29, 2015 14:00
Show Gist options
  • Save ljsc/11072974 to your computer and use it in GitHub Desktop.
Save ljsc/11072974 to your computer and use it in GitHub Desktop.
YAFBI: Yet Another Fizz-Buzz Implementation
(defn divided-by?
"Divisibilty predicate. Returns true iff a can be evenly divided by b."
[a b]
(= (mod b a) 0))
(defn int->fizz-buzz
"Convert a single integer n to its Fizzbuzz output."
[n]
(condp divided-by? n
15 "Fizzbuzz"
5 "Buzz"
3 "Fizz"
n))
(defn fizz-buzz
"Run the fizz-buzz program to output the sequence upto count."
[count]
(dorun (dec count)
(->> (iterate inc 1)
(map (comp println int->fizz-buzz)))))
(fizz-buzz 100)
--
-- Haskell version for comparison, just because ;)
--
module Fizzbuzz where
import Control.Conditional (condDefault)
doFizz :: Int -> IO ()
doFizz = sequence_ . map putStrLn . fizzbuzz
fizzbuzz :: Int -> [String]
fizzbuzz = map fizzbuzz1 . enumFromTo 1
divides :: Int -> Int -> Bool
m `divides` n = n `mod` m == 0
fizzbuzz1 :: Int -> String
fizzbuzz1 n = condDefault (show n) $
[ (15 `divides` n, "Fizzbuzz")
, (5 `divides` n, "Buzz")
, (3 `divides` n, "Fizz")
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment