为什么不是';t show在haskell中被视为转换?

为什么不是';t show在haskell中被视为转换?,haskell,type-signature,Haskell,Type Signature,我仍然很想进入哈斯克尔,但我注意到一些事情让我很恼火 在这本书中,有一部分展示了在模式匹配中使用卫士,在这本书中,它是一个计算人的bmi的小函数,它有点像这样(部分稍微改变,以不侵犯版权或其他): bmiCalc::(RealFloat a)=>a->a->String 体重身高 |bmi a->a->字符串 文件号:hs:1:16-48 可能的解决方案: 将(显示a)添加到 bmiCalc::RealFloat a=>a->a->String的类型签名 在“(++)”的第二个参数中,即“sho

我仍然很想进入哈斯克尔,但我注意到一些事情让我很恼火

在这本书中,有一部分展示了在模式匹配中使用卫士,在这本书中,它是一个计算人的bmi的小函数,它有点像这样(部分稍微改变,以不侵犯版权或其他):

bmiCalc::(RealFloat a)=>a->a->String
体重身高
|bmi a->a->字符串
文件号:hs:1:16-48
可能的解决方案:
将(显示a)添加到
bmiCalc::RealFloat a=>a->a->String的类型签名
在“(++)”的第二个参数中,即“show bmi”
在表达式中:“skinny”++表示体重指数
在“bmiCalc”的方程式中:
体重身高

|bmi将类型签名更改为:

bmiCalc :: (RealFloat a, Show a) => a -> a -> String

因为您想使用
show
类型类中的成员函数
show
;但是您没有在函数约束中指定,ghci无法推断这是正确的。

RealFloat不是可显示的类型。您必须添加一个show约束。

您是否尝试了错误消息中的建议(就在“可能的修复”之后)?类似的Java等价物将是
show
show
接口的一种方法,并且您的值
a
不需要实现该接口,因此有一个编译时类型检查错误——与Java中发生的情况相同。以前的情况是,typeclass
RealFloat
Show
作为其先决条件之一(通过
Num
),但不久前就发生了变化。LYAH在这方面已经过时了(请参阅,搜索“加入Num”)。有趣的是,我以前尝试过这样做,但没有成功。。。不知怎么的,现在是。。无论如何谢谢你!出现此类错误时,最简单的解决方法是删除类型签名,在ghci中重新加载文件,然后键入
:t bmiCalc
。这就是我在最后添加所有类型签名的方式。
bmiCalc :: (RealFloat a) => a -> a -> String
bmiCalc weight height
    | bmi <= 18.5 = "skinny, " ++ show bmi
    | bmi <= 25.0 = "normal, " ++ show bmi
    | bmi <= 30.0 = "fat, "    ++ show bmi
    | otherwise   = "obese, "  ++ show bmi
    where bmi = weight / height ^ 2
Could not deduce (Show a) arising from a use of `show'
from the context (RealFloat a)
  bound by the type signature for
             bmiCalc :: RealFloat a => a -> a -> String
  at file.hs:1:16-48
Possible fix:
  add (Show a) to the context of
    the type signature for bmiCalc :: RealFloat a => a -> a -> String
In the second argument of `(++)', namely `show bmi'
In the expression: "skinny, " ++ show bmi
In an equation for `bmiCalc':
    bmiCalc weight height
      | bmi <= 18.5 = "skinny, " ++ show bmi
      | bmi <= 25.0 = "normal, " ++ show bmi
      | bmi <= 30.0 = "fat, " ++ show bmi
      | otherwise = "obese, " ++ show bmi
      where
          bmi = weight / height ^ 2
Failed, modules loaded: none.
bmiCalc :: (RealFloat a, Show a) => a -> a -> String