aboutsummaryrefslogtreecommitdiff
path: root/Haskell-book/14/morse/src/Main.hs
diff options
context:
space:
mode:
authorEugen Wissner <belka@caraus.de>2025-12-11 10:28:11 +0100
committerEugen Wissner <belka@caraus.de>2025-12-11 10:28:11 +0100
commit98329e0a3dd4f78b5d815ac3896272ec70904901 (patch)
tree80f9c56cfe2ac20232358f236d32e84bd683be1b /Haskell-book/14/morse/src/Main.hs
parent3624c712d72d246f21d4e710cec7c11e052e0326 (diff)
downloadbook-exercises-98329e0a3dd4f78b5d815ac3896272ec70904901.tar.gz
Add remaining haskell book exercises
Diffstat (limited to 'Haskell-book/14/morse/src/Main.hs')
-rw-r--r--Haskell-book/14/morse/src/Main.hs59
1 files changed, 59 insertions, 0 deletions
diff --git a/Haskell-book/14/morse/src/Main.hs b/Haskell-book/14/morse/src/Main.hs
new file mode 100644
index 0000000..1f73b90
--- /dev/null
+++ b/Haskell-book/14/morse/src/Main.hs
@@ -0,0 +1,59 @@
+module Main where
+
+import Control.Monad (forever, when)
+import Data.List (intercalate)
+import Data.Traversable (traverse)
+import Morse (stringToMorse, morseToChar)
+import System.Environment (getArgs)
+import System.Exit (exitFailure, exitSuccess)
+import System.IO (hGetLine, hIsEOF, stdin)
+
+convertToMorse :: IO ()
+convertToMorse = forever $ do
+ weAreDone <- hIsEOF stdin
+ when weAreDone exitSuccess
+
+ line <- hGetLine stdin
+ convertLine line
+
+ where convertLine line = do
+ let morse = stringToMorse line
+ case morse of
+ (Just str) -> putStrLn (intercalate " " str)
+ Nothing -> do
+ putStrLn $ "ERROR: " ++ line
+ exitFailure
+
+convertFromMorse :: IO ()
+convertFromMorse = forever $ do
+ weAreDone <- hIsEOF stdin
+ when weAreDone exitSuccess
+
+ line <- hGetLine stdin
+ convertLine line
+
+ where
+ convertLine line = do
+ let decoded :: Maybe String
+ decoded = traverse morseToChar (words line)
+
+ case decoded of
+ (Just s) -> putStrLn s
+ Nothing -> do
+ putStrLn $ "ERROR: " ++ line
+ exitFailure
+
+main :: IO ()
+main = do
+ mode <- getArgs
+ case mode of
+ [arg] ->
+ case arg of
+ "from" -> convertFromMorse
+ "to" -> convertToMorse
+ _ -> argError
+ _ -> argError
+
+ where argError = do
+ putStrLn "Please specify the first argument as being 'from' or 'to' morse, such as: morse to"
+ exitFailure \ No newline at end of file