【发布时间】:2018-04-16 18:20:41
【问题描述】:
所以我正在尝试写一点 Haskell,我遇到了这个让我想把头撞到墙上的问题。
printGrade points = case points of
points | 0 <= points && points < 50 -> 5.0
points | 50 <= points && points < 54 -> 4.0
points | 54 <= points && points < 58 -> 3.7
points | 58 <= points && points < 62 -> 3.3
points | 62 <= points && points < 66 -> 3.0
points | 66 <= points && points < 70 -> 2.7
points | 70 <= points && points < 74 -> 2.3
points | 74 <= points && points < 78 -> 2.0
points | 78 <= points && points < 82 -> 1.7
points | 82 <= points && points < 86 -> 1.3
points | 86 <= points && points < 100 -> 1.0
note a b c d =
if d > 100 || c > 20
then return "Wrong input"
else if a == False || b == False
then printGrade d
else printGrade (c + d)
当我尝试运行代码时,它编译没有问题,但实际调用该函数时会出现此错误
<interactive>:91:1: error:
• Ambiguous type variable ‘m0’ arising from a use of ‘print’
prevents the constraint ‘(Show (m0 [Char]))’ from being solved.
Probable fix: use a type annotation to specify what ‘m0’ should be.
These potential instances exist:
instance Show a => Show (Maybe a) -- Defined in ‘GHC.Show’
instance (Show a, Show b) => Show (a, b) -- Defined in ‘GHC.Show’
instance (Show a, Show b, Show c) => Show (a, b, c)
-- Defined in ‘GHC.Show’
...plus 13 others
...plus two instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In a stmt of an interactive GHCi command: print it
我知道它与然后返回“错误输入”有关,但我不知道解决此问题的方法,因为我必须在某些时候打印出一个字符串。 (我试过 show/print/putStrLn 导致另一个错误)
【问题讨论】:
-
你为什么在这里使用
case,而只使用警卫? -
哈哈哈我不知道当我删除案例时它根本不起作用
-
不幸的是,这个错误经常出现。
return不是 Haskell 中的 关键字:它是用于 monad 的函数。因此,我建议您不要使用它,除非您知道自己在做什么。 -
任何我可以使用而不是 return 来打印出字符串而不会导致此错误?
-
你应该从它们的类型开始编写这些函数。如果返回类型是
Double,则不能返回字符串(当然也不能在像return "abc"这样的monad 中返回字符串)。如果你想出错,你可以使用if ... then 2.71 else error "message",但要明白这个错误会在评估时使程序崩溃,调用者将无法捕捉到错误并处理它。有时这已经足够了。表达式error ".."适合任何类型。