[英]Haskell types/type conversion (sqrt,floor)
I'm trying to implement the Cantor Pairing using Haskell. 我正在尝试使用Haskell实现Cantor配对。 The encoding of a list of ints is working fine, the decoding however is just not working due to type errors. 整数列表的编码工作正常,但是由于类型错误,解码只是无效。
I tried nearly everything I could think of, but nothing would work out: 我几乎尝试了所有我能想到的,但没有任何效果:
cantorDecode :: Integer -> [Integer] -> [Integer]
cantorDecode e zs
| length zs == 0 = cantorDecode y [x,y]
| head zs == 0 = map toInteger $ tail zs
| otherwise = cantorDecode y ((head zs)-1 : (tail zs) ++ [x,y])
where
a = fromRational e
w = floor ((s-1.0)/2.0)
s = fromIntegral $ sqrt(8.0*e+1.0) :: Double
t = fromRational $ (w^2+w)/2.0
y = toInteger $ e - (toInteger $ floor t)
x = toInteger $ (toInteger w) - (toInteger y)
As you can see, I'm using sqrt
, floor
and other things, so it's a bit messy... 如您所见,我正在使用sqrt
, floor
和其他东西,所以有点混乱...
OK that does look desperate. 好的,看起来确实很绝望。 A couple points: 几点:
fromRational
, since you have no actual Rational
s here. 您当然不希望fromRational
,因为这里没有实际的Rational
。 Also, fromRational
and toFractional
are both strictly less general than their combination realToFrac
, although you don't need that either - these are all for converting between different floating point/rational types, but you have only one involved, Double
. 另外, fromRational
和toFractional
都比其realToFrac
组合严格不通用,尽管您都不需要-它们都用于在不同的浮点/有理类型之间进行转换,但是您只有一个Double
涉及。 toInteger
, which is only for converting between different Integral
types. 您不需要toInteger
,它仅用于在不同的Integral
类型之间进行转换。 You do want its generalization fromIntegral
which converts from an Integral
type to a general Num
. 您确实希望将其归纳为fromIntegral
,它将其从Integral
类型转换为一般Num
。 You should make a clear decision exactly which of your variables are Integer
s, and which are Double
s. 您应该做出明确的决定,确切地确定哪些变量是Integer
,哪些变量是Double
。 Then use fromIntegral
to convert from Integer
to Double
, and floor
or another similar function to convert from Double
to Integer
, when necessary. 然后在必要时使用fromIntegral
从Integer
转换为Double
,并使用floor
或其他类似函数从Double
转换为Integer
。 You have several attempts there to convert between the same type (basically, all your toInteger
s.) 您尝试过在同一类型之间转换(基本上是所有toInteger
)。
Given this, you can clean your type-conversion code up into (adding explicit type annotations for clarity): 鉴于此,您可以将类型转换代码清理成(为清楚起见添加显式类型注释):
cantorDecode :: Integer -> [Integer] -> [Integer]
cantorDecode e zs
| length zs == 0 = cantorDecode y [x,y]
| head zs == 0 = tail zs
| otherwise = cantorDecode y ((head zs)-1 : (tail zs) ++ [x,y])
where
w = floor ((s-1.0)/2.0) :: Integer
w' = fromIntegral w :: Double
s = sqrt(8.0*fromIntegral e+1.0) :: Double
t = (w'^2+w')/2.0 :: Double
y = e - floor t :: Integer
x = w - y :: Integer
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.