代码之家  ›  专栏  ›  技术社区  ›  Novak

Haskell在if-then-else语句上引发错误[重复]

  •  -1
  • Novak  · 技术社区  · 7 年前

    这个问题已经有了答案:

    我刚开始学习haskell,在加载文件时遇到问题 ghci . 在一个名为 Exercises.hs 我有一些我应该解决的预先定义的练习,这个练习给了我一个错误:

    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 "") 
    

    现在,当我试图将此文件加载到 GHCI 喜欢 ghci Exercises.hs . 错误消息如下:

    $ 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.
    

    我不知道我的代码怎么了?当我评论第一行时 ex112 = showSalary' 模块已加载,运行正常。为什么会出现这种错误?

    1 回复  |  直到 7 年前
        1
  •  3
  •   talex    7 年前

    只需给出类型:

    ex112 :: (Show a) => a -> Integer -> String        
    ex112 = showSalary'
    
    推荐文章