0

I have just started learning Haskell and I have a problem with loading a file in ghci. In a file called Exercises.hs I have some predefined exercises I should solve and this one is giving me an error:

showSalary amount bonus
   | bonus /= 0 = "Salary is " ++ show amount ++ ", and a bonus " ++ 
                  show bonus 
   | otherwise  = "Salary is " ++ show amount

-- 1.2. Give a simpler definition of 'showSalary', using only one if-then-else construct. 

ex112 = showSalary'
showSalary' amount bonus = "Salary is " ++ show amount ++ 
          (if bonus /= 0 then ", and a bonus " ++ show bonus else "") 

Now, the problem arises when I try to load this file into ghci like ghci Exercises.hs. The error message is following:

$ ghci Exercises
GHCi, version 8.4.3: http://www.haskell.org/ghc/  :? for help
[1 of 1] Compiling Exercises        ( Exercises.hs, interpreted )

Exercises.hs:31:9: error:
    • Ambiguous type variable ‘a0’ arising from a use of ‘showSalary'’
      prevents the constraint ‘(Show a0)’ from being solved.
      Relevant bindings include
        ex112 :: a0 -> Integer -> [Char] (bound at Exercises.hs:31:1)
      Probable fix: use a type annotation to specify what ‘a0’ should be.
      These potential instances exist:
        instance (Show a, Show b) => Show (Either a b)
          -- Defined in ‘Data.Either’
        instance Show GeneralCategory -- Defined in ‘GHC.Unicode’
        instance Show Ordering -- Defined in ‘GHC.Show’
        ...plus 24 others
        ...plus 49 instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    • In the expression: showSalary'
      In an equation for ‘ex112’: ex112 = showSalary'
   |
31 | ex112 = showSalary'
   |         ^^^^^^^^^^^
Failed, no modules loaded.

I don't know what is wrong with my code? When I comment out the first line ex112 = showSalary' the module is loaded and it runs without problem. Why is this error arising?

duplode
  • 33,731
  • 7
  • 79
  • 150
Novak
  • 2,143
  • 1
  • 12
  • 22

1 Answers1

3

Just give it the type:

ex112 :: (Show a) => a -> Integer -> String        
ex112 = showSalary'
talex
  • 17,973
  • 3
  • 29
  • 66
  • This is correct, thanks :) But Can you explain why this happens? Why do I have to give it the type? – Novak Nov 30 '18 at 10:03
  • You can find explanation here https://stackoverflow.com/questions/32496864/what-is-the-monomorphism-restriction – talex Nov 30 '18 at 10:05