我认为我的问题是我将我对 Haskell 多态性的有限知识与其他语言的重载和模板化之类的东西混淆了。在我上一个问题之后,我认为我对这些概念有了更好的把握,但是再试一次,我想不是!
无论如何,我正在尝试实现一个通用的距离函数。这很简单:
euclidean :: Integral a => [a] -> [a] -> Double
euclidean a b = sqrt . sum $ zipWith (\u v -> (u - v)^2) x y
where x = map fromIntegral a
y = map fromIntegral b
现在我想将它应用于两种向量类型(为了论证,不能重新定义):
type Vector1 = Integer
data Vector2 = Vector2 Integer Integer
在阅读了我上一个问题的答案后,我想我会使用模式匹配:
d :: a -> a -> Double
d (Vector2 x1 y1) (Vector2 x2 y2) = euclidean [x1, y1] [x2, y2]
d a b = euclidean [a] [b]
这失败了:
Couldn't match expected type `a' with actual type `Vector2'
`a' is a rigid type variable bound by
the type signature for d :: a -> a -> Double at test.hs:11:6
In the pattern: Vector2 x1 y1
In an equation for `d':
d (Vector2 x1 y1) (Vector2 x2 y2) = euclidean [x1, y1] [x2, y2]
所以我想我会小心翼翼地再次尝试类型类:
{-# LANGUAGE FlexibleInstances #-}
class Metric a where
d :: a -> a -> Double
instance Metric Vector1 where
d a b = euclidean [a] [b]
instance Metric Vector2 where
d (Vector2 x1 y1) (Vector2 x2 y2) = euclidean [x1, y1] [x2, y2]
当您预先知道您输入的类型时,这将编译并工作。d
但是,就我而言,我编写了另一个函数,它调用d
,其中类型可以是任何一种(在运行时确定)。这失败了:
No instance for (Metric a) arising from a use of `d'
Possible fix:
add (Metric a) to the context of
the type signature for someFunction :: [a] -> [a] -> [a]
In the expression: d c x
In the expression: (x, d c x)
In the first argument of `map', namely `(\ x -> (x, d c x))'
从我对上一个问题的答案的有限理解来看,我认为这是因为我的类型类中存在漏洞,这导致类型推断器进入不确定状态。
在这一点上,我有点不知所措:参数多态性和临时多态性都没有解决我的问题。因此,我的解决方案是这个烂摊子:
someFunction1 :: [Vector1] -> [Vector1] -> [Vector1]
-- Lots of code
where d a b = euclidean [a] [b]
someFunction2 :: [Vector2] -> [Vector2] -> [Vector2]
-- Exactly the same code
where d (Vector2 x1 y1) (Vector2 x2 y2) = euclidean [x1, y1] [x2, y2]
这似乎不对。我错过了什么?