Skip to content

Instantly share code, notes, and snippets.

@jamesandariese
Last active September 12, 2016 03:31
Show Gist options
  • Save jamesandariese/8e48ec22a8e538806e0d061250c8dde3 to your computer and use it in GitHub Desktop.
Save jamesandariese/8e48ec22a8e538806e0d061250c8dde3 to your computer and use it in GitHub Desktop.
haskell fizzbuzz
-- Return a list of strings of fizzbuzz from [1..]
fizzbuzz :: [[Char]]
fizzbuzz = fizzbuzz' 1
where
fizzbuzz' n =
fizzbuzzer : (fizzbuzz' (n + 1))
where fizzbuzzer
| fb3 = "Fizz"
| fb5 = "Buzz"
| fb3 && fb5 = "FizzBuzz"
| otherwise = (show n)
fb3 = n `mod` 3 == 0
fb5 = n `mod` 5 == 0
main =
mapM putStrLn (fizzbuzz)
-- prints forever. try the following to print a bounded number:
-- mapM putStrLn (take 100 fizzbuzz)
@jamesandariese
Copy link
Author

Fizzbuzz. Not the most interesting problem. I wanted to do it in Haskell though for one reason: the fizzbuzz function up there never terminates. It also doesn't use up any (significant) extra memory as it runs. The mapM and putStrLn happily consume the left side of the cons cell and call the continuation of fizzbuzz associated with the uncalculated next value of the right side of the cons cell. Meanwhile, the garbage collector collects the value that was used from the left side of the list since it no longer is referenced anywhere. mapM moves onto the head of the right side of the cons cell forcing the next cons cell to be populated with a new head (the next element) and a new continuation that will repeat the process.

Lazy evaluation!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment