Re:FizzBuzz in Haskell [pdf]
by turboponyy on Tuesday November 22, 2022 @06:58AM
(#33704791)
This is not too dissimilar to the final solution outlined in the essay, but is much more readable, in my opinion, due to its use of mappend over Maybe Strings instead of implementing the same sort of compositionality using regular function composition. Very elegant!
My version looks like the below. I didn't originate the approach but I like this spelling. It won't make total sense to non-Haskellers though.
This extends in an obvious way to FizzBuzzHissHowl, lets the Monoid instance manage concatenating the special tokens together while remembering if any of the rules have matched, and uses a monad comprehension on the Maybe monad to cleanly lift the token into the Maybe monad if the number is a multiple of whatever. The type annotation on f is added to make it a little bit clearer what is going on.The use of monoids and the monad comprehension may be slightly flashy, but the use of Maybe to remember whether a rule has triggered is second nature in Haskell.