Last active
December 6, 2023 10:15
-
-
Save gallais/35164b36b9fe8b5dd7530de47df75bbd to your computer and use it in GitHub Desktop.
Finding words that are their own rot13
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Rot13 where | |
import Control.Monad (guard) | |
import Data.Char (ord, chr, toLower, isLower) | |
import Data.Function (on) | |
import Data.List (sortBy) | |
import Data.Maybe (mapMaybe) | |
import Data.Set (Set) | |
import qualified Data.Set as Set | |
import System.Environment | |
import System.Exit | |
rot13 :: String -> String | |
rot13 = map (chr . (+ ord 'a') . (`mod` 26) . (13+) . (\ c -> c - ord 'a') . ord) | |
usage :: IO () | |
usage = putStrLn "Call the executable with no argument or --keep-uppercased-words" | |
main :: IO () | |
main = do | |
args <- getArgs | |
keepNames <- case args of | |
[] -> pure False | |
"--keep-uppercased-words" : [] -> pure True | |
_ -> do usage; exitFailure | |
rdict <- lines <$> readFile "/usr/share/dict/american-english" | |
let dict = if keepNames then rdict else filter (all isLower) rdict | |
let dictS = Set.fromList dict | |
let wms = flip mapMaybe dict $ \ w0 -> do | |
let w = map toLower w0 | |
let m = rot13 w | |
guard (m `Set.member` dictS) | |
pure (w, m) | |
mapM_ (\ (w, m) -> putStrLn (w ++ " -> " ++ m)) | |
$ sortBy (flip (compare `on` (length . fst))) wms |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment