3
\$\begingroup\$

I wrote a solution to the popularized FizzBuzz problem in Haskell to see how a functional solution looks. I'm more or less happy with my solution, except for the definition of list. It just looks sort of contorted.

Are there any language features in Haskell which can improve the readability of this code, especially the definition of list, while preserving the extensibility that table provides?

import Control.Arrow

main = mapM_ (putStrLn . fizzBuzzLogic) [1..100]

fizzBuzzLogic :: Int -> String
fizzBuzzLogic x
  | null list = show x
  | otherwise = foldl1 (++) list
  where
    list  = map snd . filter ((==0) .fst) $ map (first (mod x)) table
    table = [(3,"Fizz")
            ,(5,"Buzz")
            ] --add more modulo tokens if you wish
\$\endgroup\$
  • 1
    \$\begingroup\$ Instead of foldl1 (++) use concat \$\endgroup\$ – Bergi Apr 26 '14 at 19:15
7
\$\begingroup\$

You write:

map snd . filter ((==0) .fst) $ map (first (mod x)) table

To make it clearer that we have three operations applied one after another, I would rather write:

map snd . filter ((==0) .fst) . map (first (mod x)) $ table

But I think this gets easier to read if we merge the filter and the second map:

map snd . filter ((== 0) . mod x . fst) $ table

Some people prefer pointful style, that is, they prefer \ over .:

map snd . filter (\(number, text) -> x `mod` number == 0) $ table

Personally, I would prefer a list comprehension here:

[text | (number, text) <- table, x `mod` number == 0]
\$\endgroup\$
  • \$\begingroup\$ I agree, the list comprehension is a much clean solution here! Thanks for the detailed input! \$\endgroup\$ – recursion.ninja Apr 26 '14 at 17:26
  • \$\begingroup\$ Is there an official style guide statement for op $ op $ op $ arg vs op . op . op $ arg? I tend to prefer the former. \$\endgroup\$ – John Dvorak Dec 25 '14 at 19:50
  • 1
    \$\begingroup\$ @JanDvorak $ is considered visually noisier than .. Also, . resembles mathematical operator ∘ for function composition. Since functional languages are largely about the composition of functions, the . operator is preferred also for academic reasons. Also $ and . have different operator precedence so they are not always interchangeable! \$\endgroup\$ – recursion.ninja Jul 13 '15 at 18:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.