问题描述
我在编译时收到以下错误消息:
I get the following error message when I compile:
我的解决方案是使用findValI和findValD.但是,findValI只是将Int类型转换为Double并调用findValD.
My solution is to have findValI and findValD. However, findValI just converts the Int type to a Double and calls findValD.
我也无法对Num类型(Int,Double)进行模式匹配,因此我不能仅将类型签名更改为
Also I can't pattern match on types of Num (Int, Double) so I can't just change the type signature to
findVal :: [ValPair] -> Num -> Double
在许多语言中,我不需要其他名称.为什么在Haskell中需要其他名称?这会很难添加到语言中吗?还是那里有龙?
In many languages I wouldn't need different names. Why do I need different names in Haskell? Would this be hard to add to the language? Or are there dragons there?
推荐答案
在Haskell中,按类型分类提供了特殊的多态性(和名称重载):
Ad-hoc polymorphism (and name overloading) are provided in Haskell by typeclasses:
class CanFindVal a where
findVal :: [ValPair] -> a -> Double
instance CanFindVal Double where
findVal xs d = ...
instance CanFindVal Int where
findVal xs d = findVal xs (fromIntegral d :: Double)
请注意,在这种情况下,由于findVal
确实"需要一个Double
,所以我总是总是将它加倍,并且当我需要将其传递给int时,只需在fromIntegral
处使用fromIntegral
即可.呼叫网站.通常,当涉及的行为或逻辑实际上不同时(而不是混杂地),就需要类型类.
Note that in this case, since findVal
"really" needs a Double
, I'd just always have it take a double, and when I needed to pass it an int, just use fromIntegral
at the call site. You generally want typeclasses when there's actually different behavior or logic involved, rather than promiscuously.
这篇关于重载函数签名haskell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!