[英]Haskell types/type conversion (sqrt,floor)
我正在尝试使用Haskell实现Cantor配对。 整数列表的编码工作正常,但是由于类型错误,解码只是无效。
我几乎尝试了所有我能想到的,但没有任何效果:
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)
如您所见,我正在使用sqrt
, floor
和其他东西,所以有点混乱...
好的,看起来确实很绝望。 几点:
fromRational
,因为这里没有实际的Rational
。 另外, fromRational
和toFractional
都比其realToFrac
组合严格不通用,尽管您都不需要-它们都用于在不同的浮点/有理类型之间进行转换,但是您只有一个Double
涉及。 toInteger
,它仅用于在不同的Integral
类型之间进行转换。 您确实希望将其归纳为fromIntegral
,它将其从Integral
类型转换为一般Num
。 您应该做出明确的决定,确切地确定哪些变量是Integer
,哪些变量是Double
。 然后在必要时使用fromIntegral
从Integer
转换为Double
,并使用floor
或其他类似函数从Double
转换为Integer
。 您尝试过在同一类型之间转换(基本上是所有toInteger
)。
鉴于此,您可以将类型转换代码清理成(为清楚起见添加显式类型注释):
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.