Skip to content

Instantly share code, notes, and snippets.

@ObjectBoxPC
Created October 18, 2023 12:45
Show Gist options
  • Save ObjectBoxPC/8096610b9d0dd76b32597cb6a274f380 to your computer and use it in GitHub Desktop.
Save ObjectBoxPC/8096610b9d0dd76b32597cb6a274f380 to your computer and use it in GitHub Desktop.
Haskell program to check if two inputs (command-line arguments) are anagrams (in terms of the 26 letters in the English alphabet)
import Data.Char (toUpper)
import Data.List (sort)
import System.Environment (getArgs)
import System.Exit (exitWith, ExitCode(..))
data CheckAnagramError = NotEnoughArguments | EmptyInput
isAnagram :: String -> String -> Bool
isAnagram x y = normalize x == normalize y
where
normalize = sort . (filter (`elem` ['A'..'Z'])) . (map toUpper)
checkAnagram :: [String] -> Either CheckAnagramError Bool
checkAnagram xs = case xs of
(x:y:_) ->
if all (not . null) [x, y]
then Right (isAnagram x y)
else Left EmptyInput
_ -> Left NotEnoughArguments
main :: IO ()
main = do
args <- getArgs
let result = checkAnagram args
case result of
Right True -> do
putStrLn "Anagrams"
exitWith ExitSuccess
Right False -> do
putStrLn "Not anagrams"
exitWith $ ExitFailure 1
Left e -> do
case e of
NotEnoughArguments -> putStrLn "Not enough arguments"
EmptyInput -> putStrLn "Arguments must not be empty"
exitWith $ ExitFailure 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment