Haskell Complex x类型,其中x与实际类型Int不匹配



我正在编写一个Haskell函数,根据输入生成一个复数,但Ghci一直在抱怨类型。我的代码是

import Data.Complex
pos2com :: RealFloat x => Int -> Int -> Complex x
pos2com x y = ((x-800)/400) :+ ((y-400)/400)

当我试图把它加载到Ghci时,我得到了

? Couldn't match type ‘x’ with ‘Int’
‘x’ is a rigid type variable bound by
the type signature for:
pos2com :: forall x. RealFloat x => Int -> Int -> Complex x
at try.hs:3:1-49
Expected type: Complex x
Actual type: Complex Int
? In the expression: ((x - 800) / 400) :+ ((y - 400) / 400)
In an equation for ‘pos2com’:
pos2com x y = ((x - 800) / 400) :+ ((y - 400) / 400)
? Relevant bindings include
pos2com :: Int -> Int -> Complex x (bound at try.hs:4:1)

我想这里的问题应该是(/) :: Fractional a => a -> a -> a,并且在转换RealFloat xFractional xInt时发生了一些错误。有人能帮忙吗?

任一:xy都需要是类型x:

pos2com :: Fractional x => x -> x -> Complex x
pos2com x y = ((x - 800) / 400) :+ ((y - 400) / 400)

或者,您需要首先使用fromIntegral:将它们转换为Fractional

pos2com :: Fractional x => Int -> Int -> Complex x
pos2com x y = ((fromIntegral x - 800) / 400) :+ ((fromIntegral y - 400) / 400)

在Haskell中导航数字运算时需要理解的重要一点是,大多数运算都不会更改类型——没有像在许多语言中看到的那样自动转换。所以当你有

(x - 800) / 400

无论x是什么类型,结果都将是相同的类型。所以这里xInt,这意味着(x - 800) / 400将是Int(然后会有一个丢失的实例错误,因为您不能使用/来划分Ints——您需要使用整数划分div(。

所以构造Complex x失败了,因为Int不一定是与x相同的类型。

当我们确实需要转换时,我们通常使用fromIntegral(从积分类型转换(或realToFrac(从分数类型转换(。

最新更新