LoginSignup
4
4

More than 5 years have passed since last update.

fizzbuzzについて、パターンが増える場合に対応するケースを作ってみた

Last updated at Posted at 2015-04-05

haskellの勉強を始めたので投稿してみた

FizzBuzz.hs
module FizzBuzz where

import Data.Monoid

-- | fizzbuzzについて、パターンが増える場合に対応するケース

type ModCondition = Int
type Message = String
type FBPattern = [(ModCondition, Message)]

-- | 3:fizz 5:buzz 7:woof
-- >>> fb 1
-- "1"
-- >>> fb 3
-- "fizz"
-- >>> fb 5
-- "buzz"
-- >>> fb 7
-- "woof"
-- >>> fb 15
-- "fizzbuzz"
-- >>> fb 21
-- "fizzwoof"
-- >>> fb 35
-- "buzzwoof"
-- >>> fb 105
-- "fizzbuzzwoof"
fb :: Int -> Message
fb n = case foldl1 mappend [conv n | conv <- fbMessConvert] of
    ""    -> show n
    mess  -> mess

fbMessConvert = map getMess fbPatterns

getMess (c,m) n
    | n `mod` c == 0 = m
    | otherwise = mempty

fbPatterns :: FBPattern
fbPatterns = [(3,"fizz"),(5,"buzz"),(7,"woof")]

main :: IO()
main = print $ map fb  [1..100] 
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4