Personal tools

Haskell Quiz/Morse Code/Solution Kristof

From HaskellWiki

Jump to: navigation, search

This is a simple solution that uses the list Monad to generate all possibilities.

import Maybe
import Control.Applicative -- for <$>
 
codes = zip ['A'..'Z']
        [ ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....",
        "..", ".---" , "-.-", ".-..", "--", "-.", "---", ".--.",
        "--.-", ".-.", "...", "-" , "..-", "...-", ".--", "-..-",
        "-.--", "--.." ]
 
try_letter str (letter, code) =
    let (l,r) = splitAt (length code) str
    in if l == code then Just (letter, r) else Nothing
 
morse ""  = return ""
morse str = do (l,r) <- mapMaybe (try_letter str) codes
               (l:) <$> morse r
 
main = mapM_ putStrLn . morse . filter (`elem` ".-") =<< getLine