繁体   English   中英

Haskell类型/类型转换(sqrt,floor)

[英]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)
  1. 输入是要解码的下一个整数
  2. 输入是具有已解码整数的列表

如您所见,我正在使用sqrtfloor和其他东西,所以有点混乱...

好的,看起来确实很绝望。 几点:

  1. 您当然不希望fromRational ,因为这里没有实际的Rational 另外, fromRationaltoFractional都比其realToFrac组合严格不通用,尽管您都不需要-它们都用于在不同的浮点/有理类型之间进行转换,但是您只有一个Double涉及。
  2. 您不需要toInteger ,它仅用于在不同的Integral类型之间进行转换。 确实希望将其归纳为fromIntegral ,它将其从Integral类型转换为一般Num

您应该做出明确的决定,确切地确定哪些变量是Integer ,哪些变量是Double 然后在必要时使用fromIntegralInteger转换为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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM