import Data.List (intercalate)
fizzle :: Int -> String
fizzle n =
let ws = [(3,"Fizz"),(5,"Buzz"),(7,"Bazz")]
a = [s | (d,s) <- ws, n`rem`d == 0]
in case a of [] -> show n
otherwise -> intercalate " " a ++ "!"
main = mapM_ (putStrLn . fizzle) [1..110] newtype Words = Words { getWords :: String }
instance Semigroup Words where
Words a <> Words b = Words (a <> " " <> b)
instance Monoid Words where
mempty = Words mempty
fizzbuzz i =
maybe (show i) (<> "!") . fmap getWords . mconcat $
[ Words "fizz" <$ guard (rem i 3 == 0)
, Words "buzz" <$ guard (rem i 5 == 0)
]
but at this point I agree lists might be more clear. def fizzbuzz(i):
return "".join((["fizz"] if (i % 3) == 0 else []) +
(["buzz"] if (i % 5) == 0 else [])
) or str(i)
for i in range(1, 101):
print(fizzbuzz(i))
here is "indication of good modularity" with no monoid in sight, and we did not have to import 3 extra libraries either.
lgas•8mo ago
[1] https://gist.github.com/lgastako/d4fa392cbe85cbfae7dfa5e18c1...