繁体   English   中英

Haskell Integer和Int类型; 转换不起作用

[英]Haskell Integer and Int types; conversion not working

我正在尝试解决Project Euler问题59,我必须对具有三个字符键(全部小写)的消息进行xor解密。 在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 <- [97..122], b <- 97..122],, c <- [97..122]] let keys = [map fromIntegral [a, b, c] | a <- [97..122], b <- 97..122],, c <- [97..122]]它仍然说它有类型Integer而不是Int ,当我尝试let keys = map (map fromIntegral) keys ,以及当我使用fromInteger 这是怎么回事?

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

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

这是因为数字文字的类型(以及fromIntegral的返回类型)是多态的,所以当你写let keys = ...单态限制会启动并将数值类型默认为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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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