simplified functions, ignore non ascii characters

This commit is contained in:
Stefan Friese 2024-06-24 23:23:10 +02:00
parent e0d97a4084
commit f5d35aa555
1 changed files with 11 additions and 40 deletions

View File

@ -1,59 +1,30 @@
module Encoding.LetterToNumber
( encltn
, decltn
) where
import Data.Char (ord, chr, isAscii, isAlpha, isSpace, isDigit, toUpper, isLatin1)
import Data.List (intercalate)
import Data.Char (ord, chr, isAscii, isAlpha, isSpace, isDigit, toUpper)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BC
-- This encodes ASCII characters only and ignores all other characters
charToNumber :: Char -> ByteString
charToNumber c
| not (isAscii c) = BC.pack ""
| isAlpha c = BC.pack $ show $ ord (toUpper c) - ord 'A' + 1
| isSpace c = BC.pack "0"
| otherwise = BC.singleton c
-- | isAlpha c = show $ ord (toUpper c) - ord 'A' + 1
-- | isSpace c = "0"
-- -- | isLatin1 c = [c]
-- | otherwise = [c]
numberToChar :: String -> Char
numberToChar :: ByteString -> ByteString
numberToChar s
| s == "0" = ' '
| all isDigit s = chr $ read s + ord 'A' -1
| otherwise = head s
-- | otherwise = chr $ read s + ord 'A' - 1
| s == BC.pack "0" = BC.singleton ' '
| BC.all isDigit s = BC.singleton $ chr $ (read $ BC.unpack s) + ord 'A' - 1
| otherwise = s
encltn :: ByteString -> ByteString
encltn input = go (BC.unpack input) []
where
go :: String -> [ByteString] -> ByteString
go [] acc = BC.intercalate (BC.pack "-") (reverse acc)
go (x:xs) acc
-- | not (isAscii x) = go xs (BC.singleton x : acc)
| not (isAscii x) = error "Non-ASCII character detected"
| otherwise = go xs (charToNumber x : acc)
-- encltn input = BC.intercalate (BC.pack "-") $ map charToNumber' $ BC.unpack input
-- where
-- charToNumber' c
-- | not (isAscii c)= BC.singleton c
-- | otherwise = charToNumber c
encltn input = BC.unwords $ filter (not . BC.null) $ map charToNumber $ BC.unpack input
decltn :: ByteString -> ByteString
decltn input = BC.pack $ concatMap (processSegment . BC.unpack) $ BC.split '-' input
where
processSegment :: String -> String
processSegment s
| all isDigit s = [numberToChar s]
| otherwise = s
-- decltn input = BC.pack $ go $ BC.split '-' input
-- where
-- go :: [ByteString] -> String
-- go [] = []
-- go (x:xs) =
-- let str = BC.unpack x
-- in numberToChar str ++ go xs
-- in case all isDigit str of
-- True -> numberToChar str : go xs
-- False -> str ++ go xs
decltn input = BC.concat $ map numberToChar $ BC.words input