哈斯克尔凯撒密码

问题描述 投票:0回答:1

我在这方面遇到了麻烦。我的解密没有按预期工作。我已经尝试了一段时间,但仍然不明白为什么它显示错误。

module CaesarCipher where

shift :: Char -> Int -> Char
shift ch shift =
  let newChar = ch + shift
      alphabet = ['a' .. 'z'] ++ ['A' .. 'Z'] ++ ['0' .. '9'] ++ [' ']
  in  if elem ch alphabet then
        let wrapAround = length alphabet
        in  alphabet !! ((newChar - head alphabet) `mod` wrapAround)
    else
        ch

encrypt :: String -> Int -> String
encrypt text shift = map (shift) text

decrypt :: String -> Int -> String
decrypt text shift = map (\ch -> shift ch (-shift)) text -- Lambda function for decryption
haskell encryption
1个回答
0
投票

不要给你的参数与函数同名,使用:

encrypt :: String -> Int -> String
encrypt text s = map (`shift` s) text

decrypt :: String -> Int -> String
decrypt text s = map (`shift` (-s)) text

至于

shift
函数本身,这会产生类型错误,因为您使用
newChar = ch + shift
为例,但
ch
Char
,而
shift
Int
,所以您不能添加这些一起。您可以使用
elemIndex :: Eq a => a -> [a] -> Maybe Int
 [Hackage]
找出某个项目在列表中的索引位置,然后进行移位、取模并获取移位索引处的元素。

© www.soinside.com 2019 - 2024. All rights reserved.