2

This is a continuation to my previous post.

I'm creating a FizzBuzz function that allows 3 parameters to be entered. However, this isn't just the standard FizzBuzz program. This one allows for 2 divisors while implementing an upper range. So if div1 is divisible print "Fizz", if div2 is divisible print "buzz", and if div1 and div2 are divisible print "FizzBuzz", else print the number/integer.

I found different tutorials showing how to do the regular FizzBuzz in Haskell and modified it to be able to do as explained above.

Right now I'm getting an error and I'm not sure how to properly do this in Haskell.

fizzbuzz' :: [(Integer, String)] -> Integer -> String
fizzbuzz' ss n = foldl (\str (num, subst) -> if n `mod` num == 0 then str ++ subst else str ++ "") "" ss

fizzbuzz :: [(Integer, String)] -> Integer -> String
fizzbuzz ss n = if null str then show n else str
  where str = fizzbuzz' ss n

fb :: Integer -> Integer -> Integer -> Integer
fb x y z = mapM_ putStrLn $ map (fizzbuzz [(x, "fizz"), (y, "buzz")]) [0..z]

The error I'm getting is:

Couldn't match expected type ‘Integer’ with actual type ‘IO ()’
In the expression:
  mapM_ putStrLn $ map (fizzbuzz [(x, "fizz"), (y, "buzz")]) [0 .. z]
In an equation for ‘fb’:
    fb x y z
      = mapM_ putStrLn
        $ map (fizzbuzz [(x, "fizz"), (y, "buzz")]) [0 .. z]
Failed, modules loaded: none.

Any ideas?

Community
  • 1
  • 1
Rocket Risa
  • 383
  • 2
  • 16
  • What type do you suppose `fb` should return? Why would you think that returns an `Integer`? – Louis Wasserman Aug 13 '15 at 18:29
  • Please do **not** add the php tag unneccessarily. The fact that you know php is completely unrelated to the question. Moreover it even breaks the highlighting of code (which uses tags to select the default highlighting). – Bakuriu Aug 14 '15 at 07:13

1 Answers1

1

The problem is simply with your type signature for fb. Just remove it and your code will compile.

The correct type signature for fb is Integer -> Integer -> Integer -> IO () as you can verify by having ghci tell you with the :t command:

$ ghci Fizzbuzz.hs
Prelude> :t fb
fb :: Integer -> Integer -> Integer -> IO ()
Prelude>
ErikR
  • 51,541
  • 9
  • 73
  • 124