Personal tools

Haskell Quiz/Morse Code/Solution Kristof

From HaskellWiki

< Haskell Quiz | Morse Code
Revision as of 20:54, 23 April 2007 by Kuribas (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

This is a simple solution that uses the list Monad for generating 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