[英]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”(我知道該消息有常見的英文單詞)。 但是當我綁定keys
和message
並運行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.