Question

My first day in Haskell hands-on, encountered the classic Caesar Cipher:

import Data.Char

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

A call for offset 5 on a string delivers:

*Main> encode 5 "abc"
"fgh"

However, a negative offset -3 errs as shown below. Hence how to modify the encode function to allow for negative values in the offset ?

*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"
Was it helpful?

Solution

Put it in parenthesis:

encode (-3) "abc"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top