Skip to content

Commit

Permalink
All roads lead to traverse!
Browse files Browse the repository at this point in the history
  • Loading branch information
kutyel committed Oct 27, 2019
1 parent 600b239 commit 48c0636
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 26 deletions.
41 changes: 16 additions & 25 deletions src/Main.hs
Original file line number Diff line number Diff line change
@@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/Morse.hs
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 48c0636

Please sign in to comment.