我在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"
答案 0 :(得分:2)
将它放在括号中:
encode (-3) "abc"