Personal tools

Haskell Quiz/Morse Code/Solution Kristof

From HaskellWiki

< Haskell Quiz | Morse Code(Difference between revisions)
Jump to: navigation, search
 
 
Line 1: Line 1:
This is a simple solution that uses the list Monad for generating all possibilities.
+
This is a simple solution that uses the list Monad to generate all possibilities.
   
 
<haskell>
 
<haskell>

Latest revision as of 20:57, 23 April 2007

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