From 48c0636e685f4f9175cde83512220bf52f2737f1 Mon Sep 17 00:00:00 2001 From: kutyel Date: Sun, 27 Oct 2019 12:34:05 +0100 Subject: [PATCH] All roads lead to traverse! --- src/Main.hs | 41 ++++++++++++++++------------------------- src/Morse.hs | 2 +- 2 files changed, 17 insertions(+), 26 deletions(-) diff --git a/src/Main.hs b/src/Main.hs index 136f069..04574d7 100644 --- a/src/Main.hs +++ b/src/Main.hs @@ -1,43 +1,34 @@ module Main where import Control.Monad (forever, when) -import Data.List (intercalate) -import Data.Traversable (traverse) import Morse (morseToChar, stringToMorse) import System.Environment (getArgs) import System.Exit (exitFailure, exitSuccess) -import System.IO (hGetLine, hIsEOF, stdin) +import System.IO + +convertLine :: (String -> IO ()) -> IO () +convertLine convert = do + weAreDone <- isEOF + when weAreDone exitSuccess + -- otherwise, proceed. + line <- getLine + convert line convertToMorse :: IO () -convertToMorse = - forever $ do - weAreDone <- hIsEOF stdin - when weAreDone exitSuccess - -- otherwise, proceed. - line <- hGetLine stdin - convertLine line +convertToMorse = forever $ convertLine to where - convertLine line = do - let morse = stringToMorse line - case morse of - (Just str) -> putStrLn (intercalate " " str) + to line = + case stringToMorse line of + (Just str) -> putStrLn (unwords str) Nothing -> do putStrLn $ "ERROR: " ++ line exitFailure convertFromMorse :: IO () -convertFromMorse = - forever $ do - weAreDone <- hIsEOF stdin - when weAreDone exitSuccess - -- otherwise, proceed. - line <- hGetLine stdin - convertLine line +convertFromMorse = forever $ convertLine from where - convertLine line = do - let decoded :: Maybe String - decoded = traverse morseToChar (words line) - case decoded of + from line = + case traverse morseToChar (words line) of (Just s) -> putStrLn s Nothing -> do putStrLn $ "ERROR: " ++ line diff --git a/src/Morse.hs b/src/Morse.hs index 51a9104..6ef1e0e 100644 --- a/src/Morse.hs +++ b/src/Morse.hs @@ -59,7 +59,7 @@ charToMorse :: Char -> Maybe Morse charToMorse c = M.lookup c letterToMorse stringToMorse :: String -> Maybe [Morse] -stringToMorse s = sequence $ fmap charToMorse s +stringToMorse = traverse charToMorse morseToChar :: Morse -> Maybe Char morseToChar m = M.lookup m morseToLetter