如何在不更改类型 Metric 的情况下使我的函数 return 成为双精度函数?
How can I make my function return a double without changing type Metric?
我有一个函数 'distance' 可以计算两点之间的距离。
我的问题是该函数应该是 Metric 类型,该类型 returns 是 Double 而函数中的 sqrt returns 是 Float。
这是我的代码:
type Metric a = Point a -> Point a -> Double
type Point a = (a, a)
distance :: Floating a => Metric a
distance (a1,b1) (a2, b2) = sqrt ((a*a)+(b*b))
where a = a2 - a1
b = b2 - b1
我知道将 Metric 写为 Point a -> Point a -> a 是否可以解决我的问题,但我需要按原样使用 Metric
我也在 Haskell 中查找了如何将 float 转换为 double 但没有发现任何有用的东西
my problem is that the function should be of type Metric
, a type which returns a Double
while my sqrt
within the function returns a Float
.
sqrt
不是 return一个Float
,它return是一个与参数,也就是Floating
的一个实例(注意Floating
是一个类型类,不是和Float
一样,是一个类型).因此它的类型为 sqrt :: Floating a => a -> a
.
您可以在这里将 distance
函数特化为 distance :: Metric Double
:
distance :: Metric <b>Double</b>
distance (a1,b1) (a2, b2) = sqrt ((a*a)+(b*b))
where a = a2 - a1
b = b2 - b1
话虽如此,让 Metric
return 和 a
:
可能更有意义
type Metric2 a = Point a -> Point a -> <b>a</b>
然后使用 Floating a => Metric2 a
:
distance :: Floating a => Metric2 a
distance (a1,b1) (a2, b2) = sqrt ((a*a)+(b*b))
where a = a2 - a1
b = b2 - b1
我有一个函数 'distance' 可以计算两点之间的距离。 我的问题是该函数应该是 Metric 类型,该类型 returns 是 Double 而函数中的 sqrt returns 是 Float。 这是我的代码:
type Metric a = Point a -> Point a -> Double
type Point a = (a, a)
distance :: Floating a => Metric a
distance (a1,b1) (a2, b2) = sqrt ((a*a)+(b*b))
where a = a2 - a1
b = b2 - b1
我知道将 Metric 写为 Point a -> Point a -> a 是否可以解决我的问题,但我需要按原样使用 Metric 我也在 Haskell 中查找了如何将 float 转换为 double 但没有发现任何有用的东西
my problem is that the function should be of type
Metric
, a type which returns aDouble
while mysqrt
within the function returns aFloat
.
sqrt
不是 return一个Float
,它return是一个与参数,也就是Floating
的一个实例(注意Floating
是一个类型类,不是和Float
一样,是一个类型).因此它的类型为 sqrt :: Floating a => a -> a
.
您可以在这里将 distance
函数特化为 distance :: Metric Double
:
distance :: Metric <b>Double</b>
distance (a1,b1) (a2, b2) = sqrt ((a*a)+(b*b))
where a = a2 - a1
b = b2 - b1
话虽如此,让 Metric
return 和 a
:
type Metric2 a = Point a -> Point a -> <b>a</b>
然后使用 Floating a => Metric2 a
:
distance :: Floating a => Metric2 a
distance (a1,b1) (a2, b2) = sqrt ((a*a)+(b*b))
where a = a2 - a1
b = b2 - b1