How to deal with file ending '\' in strings haskell

134 Views Asked by At
import Data.Char (isAlpha)
import Data.List (elemIndex)
import Data.Maybe (fromJust)

helper = ['a'..'z'] ++ ['a'..'z'] ++ ['A'..'Z'] ++ ['A'..'Z']

rotate :: Char -> Char
rotate x | '\' = '\' 
         |isAlpha(x) = helper !! (fromJust (elemIndex x helper) + 13)
         | otherwise = x

rot13 :: String -> String
rot13 "" = ""
rot13 s = map rotate s

main = do
    print $ rot13( "Hey fellow warriors" )
    print $ rot13( "This is a test")
    print $ rot13( "This is another test" )
    print $ rot13("\604099\159558\705559&\546452\390142")
    
    n <- getLine
    print $ rot13( show n)

This is my code for ROT13 and there is an error when I try to pass file ending directly

rot13.hs:8:15: error:
    lexical error in string/character literal at character ' '
  |
8 | rotate x | '\' = '\' 

There is also an error even from if not replace just use isAlpha to filter

How to deal with this?

1

There are 1 best solutions below

0
Daniel Wagner On

As in many languages, backslash is the escape character. It's used to introduce characters that are hard or impossible to include in strings in other ways. For example, strings can't span multiple lines*, so it's impossible to include a literal newline in a string literal; and double-quotes end the string, so it's normally impossible to include a double quote in a string literal. The \n and \" escapes, respectively, covers those:

> putStrLn "before\nmiddle\"after"
before
middle"after
>

Since \ introduces escape codes, it always expects to be followed by something. If you want a literal backslash to be included at that spot, you can use a second backslash. For example:

> putStrLn "before\\after"
before\after
>

The Report, Section 2.6 is the final word on what escapes are available and what they mean.

Literal characters have a similar (though not quite identical) collection of escapes to strings. So the fix to your syntax looks like this:

rotate x | '\\' = '\\'

This will let your code parse, though there are further errors to fix once you get past that.

* Yes, yes, string gaps. I know. Doesn't actually change the point, since the newline in the gap isn't included in the resulting string.