我在Haskell动手的第一天,遇到了经典的凯撒密码:
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"
放入括号内:
encode (-3) "abc"