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:  Code help requested (Tim Perry)
   2. Re:  Code help requested (Joe Van Dyk)
   3. Re:  Code help requested (Daniel Fischer)
   4.  Trivial function of type (a -> b) -> Maybe a ->  Maybe b
      (Eugen Zagorodniy)
   5. Re:  Trivial function of type (a -> b) -> Maybe a         -> Maybe b
      (Antoine Latter)
   6. Re:  Trivial function of type (a -> b) -> Maybe a -> Maybe b
      (Colin Paul Adams)
   7. Re:  Trivial function of type (a -> b) -> Maybe   a  -> Maybe b
      (Eugen Zagorodniy)


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

Message: 1
Date: Tue, 12 Jan 2010 18:38:46 -0800 (PST)
From: Tim Perry <[email protected]>
Subject: Re: [Haskell-beginners] Code help requested
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=us-ascii

I compiled the original version, Yusaka's version, and a version I wrote and 
found the following:

$ time ./Anagram_me < /usr/share/dict/words > /dev/null
real    0m2.197s
user    0m2.040s
sys     0m0.160s

$ time ./Anagram_JoeVanDyke < /usr/share/dict/words > /dev/null
real    0m4.570s
user    0m4.290s
sys     0m0.260s

pe...@emperor:~/haskell$ time ./Anagram_Yusaku < /usr/share/dict/words > 
/dev/null
real    0m1.337s
user    0m1.230s
sys     0m0.100s


From
this, it looks like mine version takes less than half the time of the
original. However, if I run a bigger dictionary (Ubuntu package
wamerican-large instead of wamerican-small) then I'm only about 30%
faster than the original. This makes me think I have some sort of
exponential data structure growth going on.  Here is my version. Can anyone 
confirm that data
structure growth is the problem with my approach?  Thanks, Tim



import Data.List as Lst
import Data.Map as Map

-- This version only displays words that have more than two
-- match in the list, and sorts by the words that got the most matches.

-- Can we do the map bit better?

main = do
  input <- getContents
  print $ anagrams $ lines input

anagrams words =
  sorted_anagrams
  where
    sorted_anagrams = sortBy sorter filtered_anagrams
    sorter a b = compare (length b) (length a)
    longEnoughWords = [x | x <- words, length x > 1]
    filtered_anagrams = [x | x <- Map.elems $ foldr insert empty $ wordPairs, 
length x > 2]
       where
         wordPairs =  zip (Prelude.map Lst.sort longEnoughWords) longEnoughWords
         insert (sorted, original) = insertWith (++) sorted [original]






----- Original Message ----
From: Daniel Fischer <[email protected]>
To: [email protected]
Sent: Tue, January 12, 2010 10:46:03 AM
Subject: Re: [Haskell-beginners] Code help requested

Am Dienstag 12 Januar 2010 17:44:12 schrieb David Frey:
> These are the numbers I got once I modified your Haskell program to only
> print out 4 results the way the Ruby program does.
>
> Your Haskell version: ~10.0 s
> My Haskell version: ~2.5 s
> Your Ruby version (Ruby 1.8): ~4.6 s
> Your Ruby version (Ruby 1.9): ~4.2 s

I sincerely hope your input file is smaller than mine :)

>
> This is my version of your program:
>
> import Control.Monad (liftM)
> import Data.Function (on)
> import Data.List (sort, sortBy)
> import qualified Data.ByteString.Char8 as B
> import qualified Data.Map as Map
>
> -- Given as stdin
> -- presents
> -- serpents
> -- no
> -- on
> -- whatever
> -- Expected Output:
> -- [["serpents","presents"],["on","no"]]
>
>
> main = do
>     input <- liftM B.lines B.getContents
>     let wordMap = buildMap $ map B.unpack input
>     print $ take 4 (listAnagrams wordMap)
>
>
> buildMap words = let
>     entries = map (\x -> (sort x, [x])) words
>     in Map.fromListWith (++) entries
>
>
> listAnagrams wordMap = let
>     anagrams = (Map.elems . Map.filter (\x -> length x > 1)) wordMap
>     in sortBy (flip (compare `on` length)) anagrams
>
>
> I found that the performance improved when I used ByteStrings to read
> the input and then unpacked to regular strings before creating the Map. 
> For some reason, using BytesStrings everywhere made the program slower. 
> Can anyone tell me why?

Yes. ByteString's sort is a bucket-sort. It allocates an array of 
256*sizeof(CSize) bytes and counts the occurrences of each character.
That's fine for long ByteStrings, but for short ByteStrings like those we 
consider here, allocating a bucket-array of 1K or 2K is incredibly much.

Sorting plain Strings is faster (not very much, though) and uses (much) 
less memory if they are short.

You can further speed up your programme if you put lists of ByteStrings in 
your Map (less memory, less GC) and unpack them only for sorting (and 
finally for output):


main = do
    input <- liftM B.lines B.getContents
    let wordMap = buildMap input
    print $ take 4 (listAnagrams wordMap)

buildMap words = let
    entries = map (\x -> (B.pack . sort $ B.unpack x, [x])) words
    in Map.fromListWith (++) entries


listAnagrams wordMap = let
    anagrams = (Map.elems . Map.filter (\x -> length x > 1)) wordMap
    -- a small speedup can be obtained by not using length:
    -- Map.filter (not . null . drop 1)
    -- or Map.filter (\l -> case l of { (_:_:_) -> True; _ -> False })
    -- if there are many long lists in the map, the speedup will become
    -- significant
    in map (map B.unpack) $ sortBy (flip (compare `on` length)) anagrams


Yours:
$ ./DFAnagrams +RTS -sstderr < /usr/share/dict/words > /dev/null                
                                                                        
./DFAnagrams +RTS -sstderr                                                      
                  
   1,218,862,708 bytes allocated in the heap                                    
                  
     544,113,420 bytes copied during GC                                         
                 
      98,018,856 bytes maximum residency (10 sample(s))                         
                 
         768,552 bytes maximum slop                                             
                 
             211 MB total memory in use (2 MB lost due to fragmentation)        
                  

  Generation 0:  2315 collections,     0 parallel,  1.98s,  2.01s elapsed
  Generation 1:    10 collections,     0 parallel,  1.28s,  1.53s elapsed

  INIT  time    0.00s  (  0.00s elapsed)
  MUT   time    3.60s  (  3.61s elapsed)
  GC    time    3.26s  (  3.54s elapsed)
  EXIT  time    0.00s  (  0.00s elapsed)
  Total time    6.86s  (  7.15s elapsed)

  %GC time      47.5%  (49.4% elapsed)

  Alloc rate    338,176,931 bytes per MUT second

  Productivity  52.4% of total user, 50.3% of total elapsed

Modified:
$ ./DFBAnagrams +RTS -sstderr < /usr/share/dict/words > /dev/null               
                                                                         
./DFBTAnagrams +RTS -sstderr                                                    
                  
   1,108,946,552 bytes allocated in the heap
     237,869,304 bytes copied during GC
      41,907,844 bytes maximum residency (10 sample(s))
       4,374,152 bytes maximum slop
              89 MB total memory in use (1 MB lost due to fragmentation)

  Generation 0:  2091 collections,     0 parallel,  1.14s,  1.19s elapsed
  Generation 1:    10 collections,     0 parallel,  0.40s,  0.50s elapsed

  INIT  time    0.00s  (  0.00s elapsed)
  MUT   time    2.90s  (  2.90s elapsed)
  GC    time    1.54s  (  1.69s elapsed)
  EXIT  time    0.00s  (  0.00s elapsed)
  Total time    4.44s  (  4.59s elapsed)

  %GC time      34.7%  (36.8% elapsed)

  Alloc rate    382,369,915 bytes per MUT second

  Productivity  65.2% of total user, 63.1% of total elapsed


versus 26.25s for the Ruby version (ruby 1.8.7).

Yay!

>
> Dave

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



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

Message: 2
Date: Tue, 12 Jan 2010 19:31:24 -0800
From: Joe Van Dyk <[email protected]>
Subject: Re: [Haskell-beginners] Code help requested
To: Tim Perry <[email protected]>
Cc: [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset=UTF-8

On Tue, Jan 12, 2010 at 6:38 PM, Tim Perry <[email protected]> wrote:
> I compiled the original version, Yusaka's version, and a version I wrote and 
> found the following:

Thanks all for your help!

What I'm most interested is getting my haskell code to be more
readable and idiomatic, as opposed to as fast as possible.


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

Message: 3
Date: Wed, 13 Jan 2010 11:56:45 +0100
From: Daniel Fischer <[email protected]>
Subject: Re: [Haskell-beginners] Code help requested
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain;  charset="iso-8859-1"

Am Mittwoch 13 Januar 2010 03:38:46 schrieb Tim Perry:
> I compiled the original version, Yusaka's version, and a version I wrote
> and found the following:
>
> $ time ./Anagram_me < /usr/share/dict/words > /dev/null
> real    0m2.197s
> user    0m2.040s
> sys     0m0.160s
>
> $ time ./Anagram_JoeVanDyke < /usr/share/dict/words > /dev/null
> real    0m4.570s
> user    0m4.290s
> sys     0m0.260s
>
> pe...@emperor:~/haskell$ time ./Anagram_Yusaku < /usr/share/dict/words >
> /dev/null real    0m1.337s
> user    0m1.230s
> sys     0m0.100s
>
>
> From
> this, it looks like mine version takes less than half the time of the
> original. However, if I run a bigger dictionary (Ubuntu package
> wamerican-large instead of wamerican-small) then I'm only about 30%
> faster than the original. This makes me think I have some sort of
> exponential data structure growth going on.  Here is my version. Can
> anyone confirm that data structure growth is the problem with my
> approach?  Thanks, Tim
>
>
>
> import Data.List as Lst
> import Data.Map as Map
>
> -- This version only displays words that have more than two
> -- match in the list, and sorts by the words that got the most matches.
>
> -- Can we do the map bit better?
>
> main = do
>   input <- getContents
>   print $ anagrams $ lines input
>
> anagrams words =
>   sorted_anagrams
>   where
>     sorted_anagrams = sortBy sorter filtered_anagrams
>     sorter a b = compare (length b) (length a)
>     longEnoughWords = [x | x <- words, length x > 1]

The words are short here, so it's not catastrophic, but

*don't use length unless you really want to know the length*

Here, use (not . null . drop 1) [an input line might be empty, so don't use 
tail], in general, instead of 

length list > k, use not . null $ drop k list;

if you want to check (length list == k),

case drop (k-1) list of
  (_:[]) -> True
 _      -> False

is O(min k (length list)), if there's a slight possibility that the list is 
much longer than k, it's safer.

However, it's unlikely that there are more than 52 one-letter words in the 
word list, so filtering out those shouldn't make it faster.

>     filtered_anagrams = [x | x <- Map.elems $ foldr insert empty $
> wordPairs, length x > 2] where

That's bad. 

Using foldr to construct the map, you must have the whole list from which 
to construct it in the memory at once - since the list takes less memory 
than the map, that is not a real problem, if you run out of memory thus, 
you would anyway - and can start constructing the map only after the entire 
reading is done - this is the real problem. 
You build a nice huge thunk that way, which may blow the stack. And it's 
slow.

foldr is for the cases where you can start returning output before the 
entire list has been consumed, a necessary condition for that is that the 
accumulation function is lazy in its second argument, like (++), (&&), 
(||).
In practically all other cases, you want foldl' (there might be a few cases 
where foldl is what you want, I haven't seen such a case yet, though).

>          wordPairs =  zip (Prelude.map Lst.sort longEnoughWords)
>                                    longEnoughWords
>          insert (sorted, original) = insertWith (++) sorted [original]

changing foldr to foldl' and insert to

insert m (sorted,original) = insertWith (++) sorted [original] m

reduces the time on my /usr/share/dict/words from 31 seconds to 8.

The difference is 0.64s vs 0.76s for 40,000 words, 1.17s vs. 1.80s on 
70,000 words, 2.12s vs. 4.22s on 120,000 words.



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

Message: 4
Date: Wed, 13 Jan 2010 16:44:26 +0200
From: Eugen Zagorodniy <[email protected]>
Subject: [Haskell-beginners] Trivial function of type (a -> b) ->
        Maybe a ->      Maybe b
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=US-ASCII

Greetings!

I looked at documentation of Maybe type and suprisingly found no
function like

maybize             :: (a -> b) -> Maybe a -> Maybe b
maybize f Nothing   =  Nothing
maybize f (Just x)  =  Just (f x)

I believe there should be a good reason for absence of such function,
say:

1) there is an idiomatic way (probably utilizing higher level
abstractions) of doing the same what 'maybize' does,
2) no one really needs it... except me,
3) ?..

Did I miss something? (It is rather about curiosity than a real problem
though).

Thanks in advance for any comments!


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

Message: 5
Date: Wed, 13 Jan 2010 08:47:42 -0600
From: Antoine Latter <[email protected]>
Subject: Re: [Haskell-beginners] Trivial function of type (a -> b) ->
        Maybe a         -> Maybe b
To: Eugen Zagorodniy <[email protected]>
Cc: [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset=UTF-8

On Wed, Jan 13, 2010 at 8:44 AM, Eugen Zagorodniy
<[email protected]> wrote:
> Greetings!
>
> I looked at documentation of Maybe type and suprisingly found no
> function like
>
> maybize             :: (a -> b) -> Maybe a -> Maybe b
> maybize f Nothing   =  Nothing
> maybize f (Just x)  =  Just (f x)
>

Have you looked at:

fmap :: Functor f => (a -> b) -> f a -> f b

It will do what you want, and has the bonus of doing the same
operation for a lot more structures.

Antoine

http://haskell.org/ghc/docs/latest/html/libraries/base-4.2.0.0/Prelude.html#v:fmap


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

Message: 6
Date: Wed, 13 Jan 2010 14:47:51 +0000
From: Colin Paul Adams <[email protected]>
Subject: Re: [Haskell-beginners] Trivial function of type (a -> b) ->
        Maybe a -> Maybe b
To: Eugen Zagorodniy <[email protected]>
Cc: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=us-ascii

>>>>> "Eugen" == Eugen Zagorodniy <[email protected]> writes:

    Eugen> Greetings!  I looked at documentation of Maybe type and
    Eugen> suprisingly found no function like

    Eugen> maybize :: (a -> b) -> Maybe a -> Maybe b maybize f Nothing
    Eugen> = Nothing maybize f (Just x) = Just (f x)

Isn't that fmap?
-- 
Colin Adams
Preston Lancashire


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

Message: 7
Date: Wed, 13 Jan 2010 17:01:13 +0200
From: Eugen Zagorodniy <[email protected]>
Subject: Re: [Haskell-beginners] Trivial function of type (a -> b) ->
        Maybe   a  -> Maybe b
To: Antoine Latter <[email protected]>
Cc: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=UTF-8

Wed, 13 Jan 2010 08:47:42 -0600 Antoine Latter:
> On Wed, Jan 13, 2010 at 8:44 AM, Eugen Zagorodniy
> <[email protected]> wrote:
> > Greetings!
> >
> > I looked at documentation of Maybe type and suprisingly found no
> > function like
> >
> > maybize             :: (a -> b) -> Maybe a -> Maybe b
> > maybize f Nothing   =  Nothing
> > maybize f (Just x)  =  Just (f x)
> >
> 
> Have you looked at:
> 
> fmap :: Functor f => (a -> b) -> f a -> f b
> 
> It will do what you want, and has the bonus of doing the same
> operation for a lot more structures.

Sure that is it. I should pay more attention to standard type classes.

Thanks!


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

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


End of Beginners Digest, Vol 19, Issue 9
****************************************

Reply via email to