[Haskell-beginners] Re: Simplifying code

edgar klerks edgar.klerks at gmail.com
Wed Feb 10 08:31:56 EST 2010


He Daniel,

I used your showTree function because it works better than mine. I also
think the program is now truly functional. I will try to implement the other
tree on my own to see how it goes.

It now looks like this:

module Main where
import Data.Char
import System
import qualified Data.Map as M
import Control.Applicative ((<$>))

--- CONFIG SECTION ---

-- add the characters you want to permutate here--
rules :: Rules
rules = M.fromList [
        'a' ==> "@",
        'l' ==> "|",
        'w' ==> "\\|/",
        'v' ==> "\\/",
        'o' ==> "0"]



data WordTree = Chain String WordTree
        |   Choice String WordTree String WordTree
        |   Stop
        deriving Show

--instance Show WordTree where
--      show = unlines.showTree

type Rules = M.Map Char [Char]

infixl 4 ==>
(==>) :: a -> b -> (a, b)
a ==> b = (a, b)



buildTree :: String -> Rules -> WordTree
buildTree [] r = Stop
buildTree (c:cs) r = case M.lookup c r of
                        Just a ->  let p = buildTree cs r
                                   in Choice a p [c] p
                        Nothing -> Chain [c] $ buildTree cs r

showTree :: WordTree -> [String]
showTree (Chain a b) = [a ++ xs | xs <- showTree b]
showTree (Choice a b c d) = [a ++ xs | xs <- showTree b] ++ [c ++ ys | ys <-
showTree d]
showTree Stop = [""]

main :: IO ()
main = do
        filename <- head <$> getArgs
        wordlist <- readFile $ filename
        let a = (flip buildTree $ rules) <$> (lines wordlist) >>= showTree
        mapM_ putStrLn a
~

On Wed, Feb 10, 2010 at 1:47 PM, edgar klerks <edgar.klerks at gmail.com>wrote:

> He  Daniel,
>
>  I use the Data.Map now, this makes it way more flexibler
>
>
> data WordTree
>>    = Branch [(Char, WordTree)]
>>    | Tip
>>
>>
> I only don't use this type of Tree. I am not sure how it works, but it
> looks good, so I will experiment with it. Is it a so called rose tree? (Then
> I can find some articles about it).
>
>
>>
>> Share the subtree,
>>                        Just a -> let st = buildTree cs r
>>                                  in Choice (a,st) (c,st)
>>
>> Stupid thing not to do, think I overlooked it :)
>
> Thanks again.
>
> Edgar
>



-- 
Flatliner ICT Service,
Email: Edgar.klerks at gmail.com,
Tel: +31727851429
Fax: +31848363080
Skype: edgar.klerks
Website: flatlinerict.nl
Adres: Koelmalaan 258,
1813JD, Alkmaar
Nederland
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20100210/964f8830/attachment.html


More information about the Beginners mailing list