【问题标题】:Haskell Integer and Int types; conversion not workingHaskell Integer 和 Int 类型;转换不起作用
【发布时间】:2015-01-23 02:28:19
【问题描述】:

我正在尝试解决 Project Euler 问题 59,我必须对具有三个字符密钥(全小写)的消息进行异或解密。在 ASCII 中,这意味着所有键的集合是

let keys = [[a, b, c] | a <- [97..122], b <- [97..122], c <- [97..122]]

以下函数将一起启发式地解密它:

decrypt :: [Int] -> [Int] -> [Char]
decrypt msg xs = map chr $ zipWith xor msg $ (concat . repeat) xs

try :: [[Int]] -> [Int] -> [Char]
try kys msg = head $ filter (isInfixOf "the") $ map (decrypt msg) kys

基本上我一直在尝试使用密钥,直到其中一个解密消息以在其中包含“the”(我知道该消息具有常见的英文单词)。但是当我绑定 keysmessage 并运行 try keys message 我得到

Couldn't match expected type `Int' with actual type `Integer'
    Expected type: [[Int]]
      Actual type: [[Integer]]
    In the first argument of `try', namely `keys'
    In the expression: try keys message

现在,即使我说let keys = [map fromIntegral [a, b, c] | a &lt;- [97..122], b &lt;- 97..122],, c &lt;- [97..122]],它仍然说它具有Integer 类型而不是Int,当我尝试let keys = map (map fromIntegral) keys 时,以及当我使用fromInteger 时也是如此。怎么回事?

【问题讨论】:

    标签: haskell types


    【解决方案1】:

    问题是keys的类型默认为[[Integer]]。通过在定义keys 时添加类型注释来覆盖它:

    let keys = ... :: [[Int]]
    

    这是因为数字字面量的类型(以及 fromIntegral 的返回类型)是多态的,所以当您编写 let keys = ... 时,monomorphism restriction 会启动并将数字类型默认为 Integer,除非它们是以其他方式受到限制。

    > let x = 42 
    > :t x
    x :: Integer
    > let y = 42 :: Int
    > :t y
    y :: Int
    

    另一个解决方案是禁用单态限制。那么keys 将是一个多态值,当您尝试使用它时,它将专门用于[[Int]]

    > :set -XNoMonomorphismRestriction
    > let x = 42
    > :t x
    x :: Num b => b
    

    【讨论】:

    • 如果将来有人阅读这个问题,请注意let keys = [[a, b, c] | a &lt;- map fromIntegral [97..122] :: [Int], b &lt;- map fromIntegral [97..122] :: [Int], c &lt;- map fromIntegral [97..122] :: [Int]] 是修复它的精确代码。另外,谢谢 hammar,我不知道这种类型的转换。
    • @jclancy 如果您为(至少)一个文字指定类型为 Int,或为(至少)一个 [97 .. 122] 列表指定 [Int],或 [[Int]]对于keys,您不需要任何fromIntegral
    • 啊,由于某种原因,以前对我不起作用,也许是错字。那么最好的解决方案是let keys = [[a, b, c] | a &lt;- [97..122], b &lt;- [97..122], c &lt;- [97..122]] :: [[Int]]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-29
    • 1970-01-01
    • 2012-02-27
    • 1970-01-01
    • 1970-01-01
    • 2014-01-07
    • 2018-03-16
    相关资源
    最近更新 更多