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.  Code help requested (Joe Van Dyk)
   2. Re:  Code help requested (David Frey)
   3. Re:  Code help requested (Yusaku Hashimoto)
   4. Re:  Code help requested (Daniel Fischer)
   5. Re:  Code help requested (David Frey)
   6. Re:  Code help requested (Daniel Fischer)


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

Message: 1
Date: Mon, 11 Jan 2010 17:22:49 -0800
From: Joe Van Dyk <[email protected]>
Subject: [Haskell-beginners] Code help requested
To: beginners <[email protected]>
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset=UTF-8

I've written two versions of the same program, one in ruby and one in
haskell.  Given words on stdin, find all the anagrams in those words.
For nicer display, we're only going to display the top 3 results.

I'm obviously new to haskell.  The ruby version runs about 5x as fast
on a large file.   How can I improve the haskell version?

http://gist.github.com/274774

# Ruby version
input = STDIN.read.split("\n")
result = Hash.new([])
input.each do |word|
  sorted_word = word.split('').sort.join
  result[sorted_word] += [word]
end
values = result.values.sort { |a, b| b.size <=> a.size }
p values[0..3]

# Haskell version
import List
import qualified Data.Map as Map

-- Given as stdin
-- presents
-- serpents
-- no
-- on
-- whatever
-- Expected Output:
-- [["serpents","presents"],["on","no"]]

-- This version only displays words that have more than one
-- 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)
    filtered_anagrams = Map.elems $ Map.filter filter_function all_anagrams
    filter_function words = length words > 1
    all_anagrams = do_anagrams words Map.empty
    do_anagrams [] result = result
    do_anagrams words result = do_anagrams
                                 (tail words)
                                 (Map.unionWith
                                   (++)
                                   (Map.fromList
[(sorted_current_word, [current_word])])
                                   result)
      where
        current_word = head words
        sorted_current_word = sort current_word



-- 
Joe Van Dyk
http://fixieconsulting.com


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

Message: 2
Date: Mon, 11 Jan 2010 18:43:58 -0800
From: David Frey <[email protected]>
Subject: Re: [Haskell-beginners] Code help requested
To: [email protected]
Message-ID: <[email protected]>
Content-Type: Text/Plain;  charset="us-ascii"

On January 11, 2010 5:22:49 pm Joe Van Dyk wrote:
> I've written two versions of the same program, one in ruby and one in
> haskell.  Given words on stdin, find all the anagrams in those words.
> For nicer display, we're only going to display the top 3 results.
> 
> I'm obviously new to haskell.  The ruby version runs about 5x as fast
> on a large file.   How can I improve the haskell version?
> 
> http://gist.github.com/274774
> 
> # Ruby version
> input = STDIN.read.split("\n")
> result = Hash.new([])
> input.each do |word|
>   sorted_word = word.split('').sort.join
>   result[sorted_word] += [word]
> end
> values = result.values.sort { |a, b| b.size <=> a.size }
> p values[0..3]
> 
> # Haskell version
> import List
> import qualified Data.Map as Map
> 
> -- Given as stdin
> -- presents
> -- serpents
> -- no
> -- on
> -- whatever
> -- Expected Output:
> -- [["serpents","presents"],["on","no"]]
> 
> -- This version only displays words that have more than one
> -- 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)
>     filtered_anagrams = Map.elems $ Map.filter filter_function all_anagrams
>     filter_function words = length words > 1
>     all_anagrams = do_anagrams words Map.empty
>     do_anagrams [] result = result
>     do_anagrams words result = do_anagrams
>                                  (tail words)
>                                  (Map.unionWith
>                                    (++)
>                                    (Map.fromList
> [(sorted_current_word, [current_word])])
>                                    result)
>       where
>         current_word = head words
>         sorted_current_word = sort current_word
> 


Can you provide a link to the data you are using as input?  I ran your program 
over a list of 15000 words and it finished in 0.4 seconds.


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

Message: 3
Date: Tue, 12 Jan 2010 15:27:12 +0900
From: Yusaku Hashimoto <[email protected]>
Subject: Re: [Haskell-beginners] Code help requested
To: Joe Van Dyk <[email protected]>
Cc: beginners <[email protected]>
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset=UTF-8

Hello,

I forked your gist and made some changes: http://gist.github.com/274956

The main change is use foldl' instead of explicit recursion (HLint may
point this out.) This gives us clearness and strictness.

And It runs faster than ruby's one on my 2GHz MacBook =)

I used ruby-1.9.1 for ruby interpreter, and GHC-6.12.1 for haskell compiler.

time ruby ./anagram.rb < /usr/share/dict/words
[["caret", "carte", "cater", "crate", "creat", "creta", "react",
"recta", "trace"], ["ester", "estre", "reest", "reset", "steer",
"stere", "stree", "terse", "tsere"], ["angor", "argon", "goran",
"grano", "groan", "nagor", "orang", "organ", "rogan"]]

real    0m4.620s
user    0m4.473s
sys     0m0.150s

ghc --make anagram
time ./anagram < /usr/share/dict/words
[["caret","carte","cater","crate","creat","creta","react","recta","trace"],["angor","argon","goran","grano","groan","nagor","orang","organ","rogan"],["ester","estre","reest","reset","steer","stere","stree","terse","tsere"]]

real    0m3.797s
user    0m3.613s
sys     0m0.173s

Each output is slightly different because of spec of Hash in ruby 1.9.

see also:
http://www.igvita.com/2009/02/04/ruby-19-internals-ordered-hash/
http://hackage.haskell.org/packages/archive/containers/0.2.0.1/doc/html/Data-Map.html#v:elems

Cheers
-- nwn

On Tue, Jan 12, 2010 at 10:22 AM, Joe Van Dyk <[email protected]> wrote:
> I've written two versions of the same program, one in ruby and one in
> haskell.  Given words on stdin, find all the anagrams in those words.
> For nicer display, we're only going to display the top 3 results.
>
> I'm obviously new to haskell.  The ruby version runs about 5x as fast
> on a large file.   How can I improve the haskell version?
>
> http://gist.github.com/274774
>
> # Ruby version
> input = STDIN.read.split("\n")
> result = Hash.new([])
> input.each do |word|
>  sorted_word = word.split('').sort.join
>  result[sorted_word] += [word]
> end
> values = result.values.sort { |a, b| b.size <=> a.size }
> p values[0..3]
>
> # Haskell version
> import List
> import qualified Data.Map as Map
>
> -- Given as stdin
> -- presents
> -- serpents
> -- no
> -- on
> -- whatever
> -- Expected Output:
> -- [["serpents","presents"],["on","no"]]
>
> -- This version only displays words that have more than one
> -- 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)
>    filtered_anagrams = Map.elems $ Map.filter filter_function all_anagrams
>    filter_function words = length words > 1
>    all_anagrams = do_anagrams words Map.empty
>    do_anagrams [] result = result
>    do_anagrams words result = do_anagrams
>                                 (tail words)
>                                 (Map.unionWith
>                                   (++)
>                                   (Map.fromList
> [(sorted_current_word, [current_word])])
>                                   result)
>      where
>        current_word = head words
>        sorted_current_word = sort current_word
>
>
>
> --
> Joe Van Dyk
> http://fixieconsulting.com
> _______________________________________________
> Beginners mailing list
> [email protected]
> http://www.haskell.org/mailman/listinfo/beginners
>


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

Message: 4
Date: Tue, 12 Jan 2010 12:57:55 +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="utf-8"

Am Dienstag 12 Januar 2010 02:22:49 schrieb Joe Van Dyk:
> I've written two versions of the same program, one in ruby and one in
> haskell.  Given words on stdin, find all the anagrams in those words.
> For nicer display, we're only going to display the top 3 results.
>
> I'm obviously new to haskell.  The ruby version runs about 5x as fast
> on a large file.   How can I improve the haskell version?
>
> http://gist.github.com/274774
>
> # Ruby version
> input = STDIN.read.split("\n")
> result = Hash.new([])
> input.each do |word|
>   sorted_word = word.split('').sort.join
>   result[sorted_word] += [word]
> end
> values = result.values.sort { |a, b| b.size <=> a.size }
> p values[0..3]
>
> # Haskell version
> import List
> import qualified Data.Map as Map
>
> -- Given as stdin
> -- presents
> -- serpents
> -- no
> -- on
> -- whatever
> -- Expected Output:
> -- [["serpents","presents"],["on","no"]]
>
> -- This version only displays words that have more than one
> -- 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)
>     filtered_anagrams = Map.elems $ Map.filter filter_function
> all_anagrams filter_function words = length words > 1
>     all_anagrams = do_anagrams words Map.empty
>     do_anagrams [] result = result
>     do_anagrams words result = do_anagrams
>                                  (tail words)

Here be dragons.
unionWith is O(n+m) where n and m are the sizes of the two maps, the insert 
variants are O(log n). So this may be quadratic [actually, if the second 
map in unionWith is a singleton, it behaves better, but it's still much 
slower than inserts] (and very lazy, which means that without 
optimisations, all the unions form a giant thunk which overflows the stack 
for large enough input), using

all_anagrams 
    = foldl' (\m w -> Map.insertWith' (++) (sort w) [w] m) Map.empty words

, you get an O(n*log n) algorithm with sufficient strictness to not blow 
the stack. For

$ wc -l /usr/share/dict/words
380645 /usr/share/dict/words

that is a heck of a difference.

>                                  (Map.unionWith
>                                    (++)

Don't use Map.fromList [(key,value)], use Map.singleton key value instead.

>                                    (Map.fromList
> [(sorted_current_word, [current_word])])
>                                    result)
>       where
>         current_word = head words
>         sorted_current_word = sort current_word

While the original version got a stack overflow without optimisations, it 
ran with -O2, but took a *lot* of memory and was ~10% slower than the Ruby 
version. But it spent 68% of the time garbage collecting.

Change all_anagrams as above, and it uses reasonable memory (about 30% more 
than Ruby if left to choose how much to use, it can run on less than Ruby 
with +RTS -MxM, but that of course increases GC times a bit) and takes 
about a third of the time of the Ruby version (*without optimisations*, -O2 
makes only a small difference [~6%] here).

$ time ruby ./Anagrams.rb < /usr/share/dict/words > /dev/null
26.27user 0.21system 0:26.48elapsed 100%CPU

$ ./AnagramsH +RTS -sstderr < /usr/share/dict/words  > /dev/null
./AnagramsH +RTS -sstderr
   1,807,965,184 bytes allocated in the heap
     577,083,904 bytes copied during GC
      73,277,232 bytes maximum residency (12 sample(s))
         858,644 bytes maximum slop
             166 MB total memory in use (1 MB lost due to fragmentation)

  Generation 0:  3437 collections,     0 parallel,  2.47s,  2.62s elapsed
  Generation 1:    12 collections,     0 parallel,  1.07s,  1.25s elapsed

  INIT  time    0.00s  (  0.00s elapsed)
  MUT   time    5.16s  (  5.19s elapsed)
  GC    time    3.54s  (  3.86s elapsed)
  EXIT  time    0.00s  (  0.00s elapsed)
  Total time    8.70s  (  9.05s elapsed)

  %GC time      40.7%  (42.7% elapsed)

  Alloc rate    350,629,823 bytes per MUT second

  Productivity  59.3% of total user, 57.0% of total elapsed



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

Message: 5
Date: Tue, 12 Jan 2010 08:44:12 -0800
From: David Frey <[email protected]>
Subject: Re: [Haskell-beginners] Code help requested
To: [email protected]
Message-ID: <[email protected]>
Content-Type: Text/Plain;  charset="us-ascii"

On January 11, 2010 5:22:49 pm Joe Van Dyk wrote:
> I've written two versions of the same program, one in ruby and one in
> haskell.  Given words on stdin, find all the anagrams in those words.
> For nicer display, we're only going to display the top 3 results.
> 
> I'm obviously new to haskell.  The ruby version runs about 5x as fast
> on a large file.   How can I improve the haskell version?
> 
> http://gist.github.com/274774
> 
> # Ruby version
> input = STDIN.read.split("\n")
> result = Hash.new([])
> input.each do |word|
>   sorted_word = word.split('').sort.join
>   result[sorted_word] += [word]
> end
> values = result.values.sort { |a, b| b.size <=> a.size }
> p values[0..3]
> 
> # Haskell version
> import List
> import qualified Data.Map as Map
> 
> -- Given as stdin
> -- presents
> -- serpents
> -- no
> -- on
> -- whatever
> -- Expected Output:
> -- [["serpents","presents"],["on","no"]]
> 
> -- This version only displays words that have more than one
> -- 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)
>     filtered_anagrams = Map.elems $ Map.filter filter_function all_anagrams
>     filter_function words = length words > 1
>     all_anagrams = do_anagrams words Map.empty
>     do_anagrams [] result = result
>     do_anagrams words result = do_anagrams
>                                  (tail words)
>                                  (Map.unionWith
>                                    (++)
>                                    (Map.fromList
> [(sorted_current_word, [current_word])])
>                                    result)
>       where
>         current_word = head words
>         sorted_current_word = sort current_word
> 

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

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?

Dave


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

Message: 6
Date: Tue, 12 Jan 2010 19:46:03 +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 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


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

Reply via email to