Send Beginners mailing list submissions to
        [email protected]

To subscribe or unsubscribe via the World Wide Web, visit
        http://www.haskell.org/mailman/listinfo/beginners
or, via email, send a message with subject or body 'help' to
        [email protected]

You can reach the person managing the list at
        [email protected]

When replying, please edit your Subject line so it is more specific
than "Re: Contents of Beginners digest..."


Today's Topics:

   1. Re:  Simplifying code (Patrick LeBoutillier)
   2. Re:  Simplifying code (Krzysztof Skrz?tnicki)
   3. Re:  define action getInt like getLine ([email protected])
   4. Re:  Simplifying code (Daniel Fischer)
   5. Re:  Simplifying code (Patrick LeBoutillier)


----------------------------------------------------------------------

Message: 1
Date: Tue, 9 Feb 2010 16:05:36 -0500
From: Patrick LeBoutillier <[email protected]>
Subject: Re: [Haskell-beginners] Simplifying code
To: edgar klerks <[email protected]>
Cc: [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1

Hi,

I think that this is a case where you have to let the recursion do the
work for you.
Here is a solution, although it seems it generates the permutations in
a different order
than yours:

import Data.Maybe

leet = [('s', '$'), ('t', '+'), ('l', '|'), ('o', '0'), ('e', '3'),
('a', '@'), ('v', '^')]

mutateWords :: [String] -> [[String]]
mutateWords = map mutateWord

mutateWord :: String -> [String]
mutateWord [] = [[]]
mutateWord (c:cs) = concat . map perms $ mutateWord cs
  where perms cs' = map (: cs') $ mutateLetter c

-- Returns a list of possible characters for c
mutateLetter :: Char -> [Char]
mutateLetter c = c : (maybeToList $ lookup c leet)


Basically, in mutateLetter you generate a list of possible letters.
For a char that
stays the same, we return [c]. For a char that has a substitution in
the leet list,
we return [c, c'].

Then in mutateWord we process the first letter, generate all the
choices and prepend
them to all the choices for the rest of the word.


Patrick


On Tue, Feb 9, 2010 at 3:11 PM, edgar klerks <[email protected]> wrote:
> Hi All,
>
> I wrote a program which permutates a list words with some rules. For example
> if I feed it a list like:
>
> banana
> waterloo
> vraag
>
> It gives back the list:
>
> banana
> b...@nana
> b...@na
> b...@n@na
> banan@
> b...@nan@
> b...@n@
> b...@n@n@
> waterloo
> wa+erloo
> water|oo
> waterl0o
> etc
>
> However I have the feeling I am doing things to complicated. I am still a
> beginner. Would someone like to help me simplify somethings. If you think
> this is inappropriate please state also. I am not offended then. I
> understand you are offering your spare time to help me.
>
> The first thing I don't get is this. I recognize some things could be
> rewritten with a bind operator (because of the concat $ fmap), but I am
> puzzled how:
>
> mutateWords :: [Char] -> [[Char]]
> mutateWords word = nub.concat $ fmap snd <$> fmap unzip <$> ( foldr(\x z ->
>                         let char = snd x
>                             nm = number word
>                             lst = fst x
>                         in (insertAt char nm <$> lst) : z
>                 ) [[]] $ mw word )
>
>
>
>
> Here is the full code:
>
>
> import Data.List
> import System
> import System.IO
> import Control.Applicative
>
>
> ---CONFIG section
>
> leat = ['s' ==> '$', 't' ==> '+', 'l' ==> '|', 'o' ==> '0','e' ==> '3', 'a'
> ==> '@', 'v' ==> '^']
>
> leata = fst.unzip $ leat
> leatb = snd.unzip $ leat
>
> -- Perl like assoc lists
> infixl 1 ==>
> a ==> b = (a, b)
>
>
> -- Flipped fmap sometimes nicer
> infixl 4 <$$>
>
> xs <$$> f = f <$> xs
>
>
> -- first I need to find  the positions of the mutatable charachters.
> findPositions :: [Char] -> [[Int]]
> findPositions xs = take (length index) $ index <*> [xs]
>         where index = elemIndices <$> leata
>
> -- And generate all subsequences
> findSubSeq :: [Char] -> [[[Int]]]
> findSubSeq  = fmap subsequences <$> findPositions
>
>
> -- Only change elements which needs to be changed
> insertAt :: Char -> [(Int, Char)] -> [Int] -> [(Int,Char)]
> insertAt c xs ps = xs <$$> (\x ->
>                 if (fst x) `elem` ps
>                         then (fst x , c)
>                         else x
>                 )
> -- Couples character to mutable positions
> mw word = (findSubSeq word) `zip` leatb
>
> number = zip [0..]
>
> mutateWords :: [Char] -> [[Char]]
> mutateWords word = nub.concat $ fmap snd <$> fmap unzip <$> ( foldr(\x z ->
>                         let char = snd x
>                             nm = number word
>                             lst = fst x
>                         in (insertAt char nm <$> lst) : z
>                 ) [[]] $ mw word )
>
> generateAll :: [Char] -> [[Char]]
> generateAll word = g lea $ mutateWords word
>     where   g 0 words = words
>                 g n words = g (n - 1) (nub  $  words >>= mutateWords )
>                 lea = length leata
> main = do
>         filename <- getArgs
>         wordlist <- readFile $ filename !! 0
>         let a = (words wordlist) >>= generateAll
>         mapM_ putStrLn  a
>
> --
> Flatliner ICT Service,
> Email: [email protected],
> Tel: +31727851429
> Fax: +31848363080
> Skype: edgar.klerks
> Website: flatlinerict.nl
> Adres: Koelmalaan 258,
> 1813JD, Alkmaar
> Nederland
>
> _______________________________________________
> Beginners mailing list
> [email protected]
> http://www.haskell.org/mailman/listinfo/beginners
>
>



-- 
=====================
Patrick LeBoutillier
Rosemère, Québec, Canada


------------------------------

Message: 2
Date: Tue, 9 Feb 2010 22:17:49 +0100
From: Krzysztof Skrz?tnicki <[email protected]>
Subject: Re: [Haskell-beginners] Simplifying code
To: edgar klerks <[email protected]>
Cc: [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset=UTF-8

Hi

A few remarks about your code:
1. 'String' is a type synonym for [Char]. It makes types like [[Char]]
more readable (at least for me).
2. There is something imperative in the way you code: I think you rely
too much on numbers as iterators. You don't have to use numbers to
drive the program control flow. Examples:

main = do
        filename <- getArgs
        wordlist <- readFile $ filename !! 0

Why not:

main = do
        (filename:_) <- getArgs
        wordlist <- readFile filename

Or:

main = do
        filename <- head <$> getArgs
        wordlist <- readFile filename

Another example:

generateAll :: String -> [String]
generateAll word = g lea $ mutateWords word
    where   g 0 words = words
            g n words = g (n - 1) (nub  $  words >>= mutateWords )
            lea = length leata

The 'g' function can be rewritten to get rid of the index number.

Here is what I got:


-- https://mail.google.com/mail/#inbox/126b45c29341640f

import System.Environment ( getArgs )
import Control.Applicative ( (<$>) )
import Data.Set (Set)
import qualified Data.Set as Set

---CONFIG section
type Rule = (Char,Char)
infixl 1 ==>
a ==> b = (a, b)

rules :: [Rule]
rules = ['s' ==> '$',
         't' ==> '+',
         'l' ==> '|',
         'o' ==> '0',
         'e' ==> '3',
         'a' ==> '@',
         'v' ==> '^']

nubOrd :: (Ord a) => [a] -> [a]
nubOrd = Set.toList . Set.fromList

singleton x = [x]


-- CORE PART
-- we mutate all words, rule at a time. If we run out of rules, we finish.
mutateWords :: [Rule] -> String -> [String]
mutateWords rules word = foldr (\r acc -> nubOrd (concatMap (applyRule
r) acc)) (singleton word) rules
-- apply one rule to one word. the result is a list of words.
applyRule :: Rule -> String -> [String]
applyRule (old,new) wrd = aux wrd where
    aux [] = [[]]
    -- we may or may not apply our rule here.
    aux (c:cs) | c == old  = [ c':suf | suf <- aux cs, c' <- [old,new] ]
               | otherwise = [ c :suf | suf <- aux cs ]

main = do
        (filename:_) <- getArgs
        wordlist <- words <$> readFile filename
        let mutated = concatMap (mutateWords rules) wordlist
        mapM_ putStrLn mutated

Best regards

Krzysztof Skrzętnicki


On Tue, Feb 9, 2010 at 21:11, edgar klerks <[email protected]> wrote:
> Hi All,
>
> I wrote a program which permutates a list words with some rules. For example
> if I feed it a list like:
>
> banana
> waterloo
> vraag
>
> It gives back the list:
>
> banana
> b...@nana
> b...@na
> b...@n@na
> banan@
> b...@nan@
> b...@n@
> b...@n@n@
> waterloo
> wa+erloo
> water|oo
> waterl0o
> etc
>
> However I have the feeling I am doing things to complicated. I am still a
> beginner. Would someone like to help me simplify somethings. If you think
> this is inappropriate please state also. I am not offended then. I
> understand you are offering your spare time to help me.
>
> The first thing I don't get is this. I recognize some things could be
> rewritten with a bind operator (because of the concat $ fmap), but I am
> puzzled how:
>
> mutateWords :: [Char] -> [[Char]]
> mutateWords word = nub.concat $ fmap snd <$> fmap unzip <$> ( foldr(\x z ->
>                         let char = snd x
>                             nm = number word
>                             lst = fst x
>                         in (insertAt char nm <$> lst) 
> : z
>                 ) [[]] $ mw word )
>
>
>
>
> Here is the full code:
>
>
> import Data.List
> import System
> import System.IO
> import Control.Applicative
>
>
> ---CONFIG section
>
> leat = ['s' ==> '$', 't' ==> '+', 'l' ==> '|', 'o' ==> '0','e' ==> '3', 'a'
> ==> '@', 'v' ==> '^']
>
> leata = fst.unzip $ leat
> leatb = snd.unzip $ leat
>
> -- Perl like assoc lists
> infixl 1 ==>
> a ==> b = (a, b)
>
>
> -- Flipped fmap sometimes nicer
> infixl 4 <$$>
>
> xs <$$> f = f <$> xs
>
>
> -- first I need to find  the positions of the mutatable charachters.
> findPositions :: [Char] -> [[Int]]
> findPositions xs = take (length index) $ index <*> [xs]
>         where index = elemIndices <$> leata
>
> -- And generate all subsequences
> findSubSeq :: [Char] -> [[[Int]]]
> findSubSeq  = fmap subsequences <$> findPositions
>
>
> -- Only change elements which needs to be changed
> insertAt :: Char -> [(Int, Char)] -> [Int] -> [(Int,Char)]
> insertAt c xs ps = xs <$$> (\x ->
>                 if (fst x) `elem` ps
>                         then (fst x , c)
>                         else x
>                 )
> -- Couples character to mutable positions
> mw word = (findSubSeq word) `zip` leatb
>
> number = zip [0..]
>
> mutateWords :: [Char] -> [[Char]]
> mutateWords word = nub.concat $ fmap snd <$> fmap unzip <$> ( foldr(\x z ->
>                         let char = snd x
>                             nm = number word
>                             lst = fst x
>                         in (insertAt char nm <$> lst) 
> : z
>                 ) [[]] $ mw word )
>
> generateAll :: [Char] -> [[Char]]
> generateAll word = g lea $ mutateWords word
>     where   g 0 words = words
>                 g n words = g (n - 1) (nub  $  words >>= 
> mutateWords )
>                 lea = length leata
> main = do
>         filename <- getArgs
>         wordlist <- readFile $ filename !! 0
>         let a = (words wordlist) >>= generateAll
>         mapM_ putStrLn  a
>
> --
> Flatliner ICT Service,
> Email: [email protected],
> Tel: +31727851429
> Fax: +31848363080
> Skype: edgar.klerks
> Website: flatlinerict.nl
> Adres: Koelmalaan 258,
> 1813JD, Alkmaar
> Nederland
>
> _______________________________________________
> Beginners mailing list
> [email protected]
> http://www.haskell.org/mailman/listinfo/beginners
>
>


------------------------------

Message: 3
Date: Tue, 09 Feb 2010 22:41:11 +0100
From: [email protected]
Subject: Re: [Haskell-beginners] define action getInt like getLine
To: Stephen Tetley <[email protected]>
Cc: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset="iso-8859-1"

ahhh, I didn't know that it's so simple with read :)

-------- Original-Nachricht --------
> Datum: Mon, 8 Feb 2010 22:26:59 +0000
> Von: Stephen Tetley <[email protected]>
> An: [email protected]
> Betreff: Re: [Haskell-beginners] define action getInt like getLine

> Hello
> 
> Upthread Daniel Fisher posted this one
> 
> getInt :: IO Int
> getInt = fmap read getLine
> 
> If you check the type of read
> 
> *GHCi> :t read
> read :: (Read a) => String -> a
> 
> 'reads' is polymorphic it will read anything from a String - well
> within reason, anything that is an instance of the Read type class.
> The "(Read a) => " part of the type signature indicates this
> constraint - that "a" ( the return type of the function read) must be
> an instance of Read.
> 
> As I wrote, you can easily derive an instance of Read by adding Read
> to the deriving clause of your data type, so the next thing to do is
> write a function swapping as few parts from Daniel's example as
> possible:
> 
> -- Here you have to make a change as you want a Month rather than an
> Int, so swap the ??? for  what you want...
> getMonth :: IO ???
> 
> -- The function definition can stay the same - none of the components
> in Daniel's definition actually depended on reading an Int:
> getMonth = fmap read getLine
> 
> 
> 
> On 8 February 2010 21:43,  <[email protected]> wrote:
> > but I have to write the action
> > readMonth :: IO Month
> > on my own and still don't have an idea how to do it
> >
> >

-- 
GRATIS für alle GMX-Mitglieder: Die maxdome Movie-FLAT!
Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01


------------------------------

Message: 4
Date: Tue, 9 Feb 2010 22:49:18 +0100
From: Daniel Fischer <[email protected]>
Subject: Re: [Haskell-beginners] Simplifying code
To: [email protected]
Cc: edgar klerks <[email protected]>
Message-ID: <[email protected]>
Content-Type: text/plain;  charset="utf-8"

Am Dienstag 09 Februar 2010 21:11:55 schrieb edgar klerks:
> Hi All,
>
> I wrote a program which permutates a list words with some rules. For
> example if I feed it a list like:
>
> banana
> waterloo
> vraag
>
> It gives back the list:
>
> banana
> b...@nana
> b...@na
> b...@n@na
> banan@
> b...@nan@
> b...@n@
> b...@n@n@
> waterloo
> wa+erloo
> water|oo
> waterl0o
> etc
>
> However I have the feeling I am doing things to complicated. I am still
> a beginner. Would someone like to help me simplify somethings.

Sure. If you don't mind that the mutations come in a different order, one 
thing that works wonders is "sequence",

sequence :: Monad m => [m a] -> m [a]

In particular, for m = [], sequence :: [[a]] -> [[a]]. Then, knowing what 
sequence does, we can write

import Control.Monad (sequence)

generateAll :: String -> [String]
generateAll word = sequence (map f word)
      where
        f c = case lookup c leat of
                Just r  -> [c,r]
                Nothing -> [c]

For each letter in the word, we generate the list of all possible 
substitutions (map f),

"woot" ~> [['w'],['o','0'],['o','0'],['t','+']]

and then sequence them, choosing each combination of substitutions once.

A little more efficient than sequence is


generateAll :: String -> [String]
generateAll word = allCombs (map f word)
      where
        f c = case lookup c leat of
                Just r  -> [c,r]
                Nothing -> [c]

allCombs :: [[a]] -> [[a]]
allCombs (l:ls) = [h:t | t <- allCombs ls, h <- l]
allCombs [] = [[]]

-- sequence (l:ls) = [h:t | h <- l, t <- sequence ls]
-- with the generators in reverse order, cf.
-- http://www.haskell.org/pipermail/haskell-cafe/2009-December/070149.html

> If you think this is inappropriate please state also.

How could it be? This list is for helping people understand Haskell better, 
exactly what you're after.

> I am not offended then. I understand you are offering your
> spare time to help me.

If one thinks one's time isn't worth it, one can just ignore the post.

>
> The first thing I don't get is this. I recognize some things could be
> rewritten with a bind operator (because of the concat $ fmap), but I am
> puzzled how:
>
> mutateWords :: [Char] -> [[Char]]
> mutateWords word = nub.concat $ fmap snd <$> fmap unzip <$> ( foldr(\x z
> ->
>
>                         let char = snd x
>                             nm = number word
>                             lst = fst x
>                         in (insertAt char nm <$> lst) : z
>                 ) [[]] $ mw word )
>
>
>
>
> Here is the full code:
>
>
> import Data.List
> import System
> import System.IO
> import Control.Applicative
>
>
> ---CONFIG section
>
> leat = ['s' ==> '$', 't' ==> '+', 'l' ==> '|', 'o' ==> '0','e' ==> '3',
> 'a' ==> '@', 'v' ==> '^']
>
> leata = fst.unzip $ leat

leata = map fst leat
leatb = map snd leat

> leatb = snd.unzip $ leat
>
> -- Perl like assoc lists
> infixl 1 ==>
> a ==> b = (a, b)
>
>
> -- Flipped fmap sometimes nicer
> infixl 4 <$$>
>
> xs <$$> f = f <$> xs
>
>
> -- first I need to find  the positions of the mutatable charachters.

No, you don't need to do that, it's in general more efficient to not care 
about positions when dealing with lists.

> findPositions :: [Char] -> [[Int]]
> findPositions xs = take (length index) $ index <*> [xs]
>         where index = elemIndices <$> leata

[f1, ..., fm] <*> [x1, ..., xn]

produces a list of length m*n, so

length (index <*> [xs]) == length index * length [xs] == length index

~> remove "take (length index) $"

>
> -- And generate all subsequences
> findSubSeq :: [Char] -> [[[Int]]]
> findSubSeq  = fmap subsequences <$> findPositions
>
>
> -- Only change elements which needs to be changed
> insertAt :: Char -> [(Int, Char)] -> [Int] -> [(Int,Char)]
> insertAt c xs ps = xs <$$> (\x ->
>                 if (fst x) `elem` ps
>                         then (fst x , c)
>                         else x
>                 )
> -- Couples character to mutable positions
> mw word = (findSubSeq word) `zip` leatb
>
> number = zip [0..]
>
> mutateWords :: [Char] -> [[Char]]
> mutateWords word = nub.concat $ fmap snd <$> fmap unzip <$> ( foldr(\x z
> ->
>
>                         let char = snd x
>                             nm = number word
>                             lst = fst x
>                         in (insertAt char nm <$> lst) : z
>                 ) [[]] $ mw word )

Okay, I give up, that's too complicated :)
One general remark.
When you have an Ord instance, "nub" is an extremely bad idea (unless your 
lists are really short), as it's quadratic in the length of the list.

map head . group . sort

or

import Data.Set

toList . fromList

are much better [O(l * log l) where l = length xs]

>
> generateAll :: [Char] -> [[Char]]
> generateAll word = g lea $ mutateWords word
>     where   g 0 words = words
>                 g n words = g (n - 1) (nub  $  words >>= mutateWords )
>                 lea = length leata
> main = do
>         filename <- getArgs
>         wordlist <- readFile $ filename !! 0
>         let a = (words wordlist) >>= generateAll
>         mapM_ putStrLn  a



------------------------------

Message: 5
Date: Tue, 9 Feb 2010 17:07:55 -0500
From: Patrick LeBoutillier <[email protected]>
Subject: Re: [Haskell-beginners] Simplifying code
To: Daniel Fischer <[email protected]>
Cc: edgar klerks <[email protected]>, [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1

Daniel,

> Sure. If you don't mind that the mutations come in a different order, one
> thing that works wonders is "sequence",
>
> sequence :: Monad m => [m a] -> m [a]
>
> In particular, for m = [], sequence :: [[a]] -> [[a]]. Then, knowing what
> sequence does, we can write
>
> import Control.Monad (sequence)
>
> generateAll :: String -> [String]
> generateAll word = sequence (map f word)
>     where
>     f c = case lookup c leat of
>                Just r  -> [c,r]
>                Nothing -> [c]

That's very nice!

One question though: In the docs sequence is described as:

  "Evaluate each action in the sequence from left to right, and
collect the results."

How is one supposed to deduce what the behavior will be for the list
monad (besides looking at the source)?


Patrick

-- 
=====================
Patrick LeBoutillier
Rosemère, Québec, Canada


------------------------------

_______________________________________________
Beginners mailing list
[email protected]
http://www.haskell.org/mailman/listinfo/beginners


End of Beginners Digest, Vol 20, Issue 16
*****************************************

Reply via email to