9️⃣

[Haskell]FizzBuzz

2024/01/09に公開

そろそろ関数型言語に挑戦してみたく、「すごいHaskell楽しく学ぼう!」を読み始めた。

一旦は3章のcase式まで読んだので、FizzBuzzをやってみた。

judge :: (Integral a, Show a) => a -> String
judge n
  | n `mod` 15 == 0 = show "FizzBuzz"
  | n `mod` 5 == 0 = show "Buzz"
  | n `mod` 3 == 0 = show "Fizz"
  | otherwise = show n

fizzBuzz :: (Integral t, Show t) => [t] -> [String]
fizzBuzz xs = [ans | x <- xs, let ans = judge x]
> nums = [1 .. 100]
> fizzBuzz nums
> ["1","2","\"fizz\"","4","\"buzz\"","\"fizz\"","7","8","\"fizz\"","\"buzz\"","11","\"fizz\"","13","14","\"fizzBuzz\"","16","17","\"fizz\"","19",...

良し悪しはわからない。とりあえずできたので成果として残しておく。

Discussion