haskell - Haskell 错误:无法将类型“a”与“Double”匹配
问题描述
我正在编写一个 Haskell 代码来查找 k 个最近邻居的列表,按照距离顺序,根据度量 d 到点列表 xs 中的点 p。我的代码如下
import Data.List
import Data.Function
type Point a = (a,a)
type Metric a = (Point a) -> (Point a) -> Double
neighbours :: Int -> Metric a -> Point a -> [Point a] -> [Point a]
neighbours k calDistance p [] = []
neighbours k calDistance p ps
| k < 0 = error "k cannot be negative"
| otherwise = take k (neighbours' (sortBy (compare `on` snd) [ (poi,dis) | (poi,dis) <- points p ps]))
neighbours' :: [(Point a, Double)] -> [Point a]
neighbours' xs = [ x | (x,y)<-xs]
points :: Point a -> [Point a] -> [(Point a, Double)]
points _ [] = []
points p1 (p2:px) = (p2,(calDistance p1 p2)): points p1 px
calDistance :: Metric Double
calDistance (x1,y1) (x2,y2) = sqrt((x1-x2)**2 + (y1-y2)**2)
错误是
• Couldn't match type ‘a’ with ‘Double’
‘a’ is a rigid type variable bound by
the type signature for:
points :: forall a. Point a -> [Point a] -> [(Point a, Double)]
at A4.hs:27:1-53
Expected type: Point Double
Actual type: Point a
• In the first argument of ‘calDistance’, namely ‘p1’
In the expression: (calDistance p1 p2)
In the first argument of ‘(:)’, namely ‘(p2, (calDistance p1 p2))’
• Relevant bindings include
px :: [Point a] (bound at A4.hs:29:15)
p2 :: Point a (bound at A4.hs:29:12)
p1 :: Point a (bound at A4.hs:29:8)
points :: Point a -> [Point a] -> [(Point a, Double)]
(bound at A4.hs:28:1)
|
29 | points p1 (p2:px) = (p2,(calDistance p1 p2)): points p1 px
|
但是,如果我将“Metric Double”更改为“Double a”,也会出现编译错误:无法将预期类型“Double”与实际类型“a”匹配。请问有人可以告诉我如何解决吗?
解决方案
见在执行
points :: Point a -> [Point a] -> [(Point a, Double)]
你打电话
calDistance :: Metric Double
这意味着,这a
必须是Double
,如果有人points
以类型的值Point Int
作为第一个参数调用会发生什么?应该如何calDistance
处理,因为它只能处理Point Double
?
该错误告诉您,这calDistance
是使用 type 的值调用的Point a
,其中a
可以是任何类型。calDistance
这与预期的 aPoint Double
作为它的第一个参数不匹配。
推荐阅读
- wpf - 找不到版本(>=3.0.0)的包 Microsoft.NETCore.App
- javascript - 带有绝对定位图像的响应式页面
- c++ - 我可以解决 unique_ptr
只存储 nullptr 时不需要 MyType 析构函数定义? - r - R中的雷达图 - 雷达图中不可见的变量值和标签太长
- python - Building pandas dataframe from JSON
- sql - SQL Server Maximum Stored Procedure Limit issue
- android-studio - adb.exe:错误:无法绑定侦听器:不允许操作
- spring - 我们如何在 IE 11 浏览器中允许使用 xframe-options 的多个域?
- c# - 如何使用事件处理程序将数据从一个表单传输到另一个表单
- java - 连接到 MSSQL 消耗太多内存