负面补偿的凯撒密码

时间:2014-03-16 13:46:22

标签: haskell encryption cryptography offset encoder

我在Haskell实践的第一天遇到了经典的Caesar Cipher:

import Data.Char

encode :: Int -> String -> String
encode offset msg = map (chr . (+ offset) . ord) msg

对字符串的offset 5调用会传递:

*Main> encode 5 "abc"
"fgh"

然而,负offset -3错误,如下所示。因此,如何修改encode函数以允许偏移量中的负值?

*Main> encode -3 "abc"

<interactive>:7:8:
    No instance for (Num (Int -> String -> String))
      arising from a use of `-'
    Possible fix:
      add an instance declaration for (Num (Int -> String -> String))
    In the expression: encode - 3 "abc"
    In an equation for `it': it = encode - 3 "abc"

<interactive>:7:9:
    No instance for (Num ([Char] -> Int -> String -> String))
      arising from the literal `3'
    Possible fix:
      add an instance declaration for
      (Num ([Char] -> Int -> String -> String))
    In the expression: 3
    In the second argument of `(-)', namely `3 "abc"'
    In the expression: encode - 3 "abc"

1 个答案:

答案 0 :(得分:2)

将它放在括号中:

encode (-3) "abc"