patternMinor
Improving a Haskell FizzBuzz Solution
Viewed 0 times
solutionimprovinghaskellfizzbuzz
Problem
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
Are there any language features in Haskell which can improve the readability of this code, especially 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 wishSolution
You write:
To make it clearer that we have three operations applied one after another, I would rather write:
But I think this gets easier to read if we merge the
Some people prefer pointful style, that is, they prefer
Personally, I would prefer a list comprehension here:
map snd . filter ((==0) .fst) $ map (first (mod x)) tableTo 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)) $ tableBut I think this gets easier to read if we merge the
filter and the second map:map snd . filter ((== 0) . mod x . fst) $ tableSome people prefer pointful style, that is, they prefer
\ over .:map snd . filter (\(number, text) -> x `mod` number == 0) $ tablePersonally, I would prefer a list comprehension here:
[text | (number, text) <- table, x `mod` number == 0]Code Snippets
map snd . filter ((==0) .fst) $ map (first (mod x)) tablemap snd . filter ((==0) .fst) . map (first (mod x)) $ tablemap snd . filter ((== 0) . mod x . fst) $ tablemap snd . filter (\(number, text) -> x `mod` number == 0) $ table[text | (number, text) <- table, x `mod` number == 0]Context
StackExchange Code Review Q#48240, answer score: 7
Revisions (0)
No revisions yet.