Haskell Quiz/FizzBuzz/Solution Syzygies

From HaskellWiki
< Haskell Quiz‎ | FizzBuzz
Revision as of 14:37, 8 July 2010 by Syzygies (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Fizz comes before Buzz comes before an integer. Fizz and Buzz stick to each other, but hide integers.

The lists for Fizz and Buzz are infinite, but zipping together with a finite list of integers, the result is finite.

module Main where

main :: IO ()
main = mapM_ putStrLn $ zipWith3 join (loop 3 "Fizz") (loop 5 "Buzz") [1..100]
  where
    xor s t = if null s then t else s
    loop n s = cycle $ replicate (n-1) [] ++ [s]
    join s t n = xor (s ++ t) (show n)

If one has enabled all warnings as errors, then the integers need an explicit type, as shown below.

The hiding logic can also be implemented by filtering for the first non-null element of a list:

module Main where
  module Main where

  main :: IO ()
  main = sequence_ $ zipWith3 join (loop 3 "Fizz") (loop 5 "Buzz") [1..100 :: Int]
    where
      loop n s = cycle $ replicate (n-1) "" ++ [s]
      join s t n = putStrLn . head $ filter (not . null) [s ++ t, show n]