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:  parser for expressions (Stephen Tetley)
   2. Re:  Performance of parallel mergesort
      (Stephen Blackheath [to Haskell-Beginners])
   3.  Maybe and IO (legajid)
   4. Re:  Maybe and IO (Stephen Blackheath [to Haskell-Beginners])
   5. Re:  Enumerated types (Brent Yorgey)
   6. Re:  Enumerated types (Tom Davie)
   7. Re:  Performance of parallel mergesort (Jon Harrop)


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

Message: 1
Date: Sun, 27 Dec 2009 20:07:45 +0000
From: Stephen Tetley <[email protected]>
Subject: Re: [Haskell-beginners] parser for expressions
To: John Moore <[email protected]>
Cc: [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1

Hi John

Whilst this won't have the learning value of working through parser
combinators yourself, here's code that uses Parsec 2 to do want you
want. Its the code from page 12 of Daan Leijen's Parsec manual [1]
except it builds a syntax tree of the expression rather than evaluates
it. I modified it for a query on Haskell cafe today, but only posted
it off list. Some formatting might get "lost in the mail" of course.

[1] 
http://research.microsoft.com/en-us/um/people/daan/download/parsec/parsec.pdf

Best wishes

Stephen


module ExprSyn where

import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Expr

runExpr :: String -> IO ()
runExpr str = case  runParser expr () "nofile"  str of
    Left err -> putStrLn "Error:" >> print err
    Right val -> print val

demo1 = runExpr "1+1"

data Expr = Mul Expr Expr
          | Div Expr Expr
          | Add Expr Expr
          | Sub Expr Expr
          | Val Integer
  deriving (Eq,Show)

expr :: Parser Expr
expr = buildExpressionParser table factor
    <?> "expression"

table :: [[Operator Char st Expr]]
table = [[op "*" Mul AssocLeft, op "/" Div AssocLeft]
        ,[op "+" Add AssocLeft, op "-" Sub AssocLeft]
        ]
  where
    op s f assoc
       = Infix (do{ string s; return f}) assoc

factor :: Parser Expr
factor = do{ char '('
           ; x <- expr
           ; char ')'
           ; return x
           }
      <|> number
      <?> "simple expression"

number :: Parser Expr
number = do{ ds <- many1 digit
           ; return (Val $ read ds)
           }
      <?> "number"


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

Message: 2
Date: Mon, 28 Dec 2009 09:56:51 +1300
From: "Stephen Blackheath [to Haskell-Beginners]"
        <[email protected]>
Subject: Re: [Haskell-beginners] Performance of parallel mergesort
To: Jon Harrop <[email protected]>
Cc: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=UTF-8

Jon,

Jon Harrop wrote:
> This is something that concerns me. Lots of discussions of parallelism,
> including the Haskell literature I have read, neglect this critical
problem
> of making sure that more time is spent doing useful work than spawning
tasks
> (sparks). How is this solved in Haskell? Do you just put magic numbers in
> that work on the machine you're currently using?

It is simply not true that Haskell literature neglects the question of
spark granularity - this is very basic and is always covered.  Read
"Real World Haskell" (available free online).  There's no 'magic
number'.  You must explicitly write your code to give the right granule
size.  I don't know the exact cost of sparking, but in my experience it
is quite small - so - as long as your granule is doing *some* real work,
it should speed up.

Jon Harrop wrote:
> The parallelism is obviously not obtaining any real speedup so something is 
> wrong. But can anyone fix it?

I've spent a bit of time measuring parallel speedup on real commercial
projects, and this is what I've found:

1. ghc-6.12 performs significantly better than ghc-6.10, and has now
been released, therefore don't use ghc-6.10.

2. The defaults generally work better than giving huge heap sizes.  Your
-K100000000 - maximum heap size per thread - will either do nothing or
cause an artificial slowdown (I have observed this with the minimum heap
size option).  Don't use it, unless experimentation proves it makes
things better.

3. +RTS -s is well worth using. It breaks the time down into MUT
(mutator) and GC (garbage collector).

4. MUT parallelization is excellent, but the parallel GC is not so good.
 If your code is GC-heavy it can spend around half of its time garbage
collecting, which doesn't parallelize so well, and this eats into the
speedup.

5. There seems to be a scalability problem with the parallel gc for
larger numbers of cores (namely 8).  I am guessing somewhat, but my
experiments tend to confirm the issue raised in Simon Marlow's (the
implementor of GHC parallelization) recent paper that it's to do with
"stopping the world" for gc.

If GHC's lack of perfection at this point in time makes Haskell "look
bad" I don't mind.  I am not selling anything, so the reader at least
knows they're getting the truth.  I see this as one of the great
advantages of open source.

Progress on GHC has been very rapid in the last couple of years, and so
I know we'll continue to see the speed of GHC's parallelism improving in
leaps and bounds.  It's actually still quite a new area, considering the
difficulty of some of the technical issues and how recent it is that
multicores are widely available on consumer hardware.  I know you
OCaml/F# guys are making great progress too.


Steve


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

Message: 3
Date: Sun, 27 Dec 2009 22:03:23 +0100
From: legajid <[email protected]>
Subject: [Haskell-beginners] Maybe and IO
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

Hi,
My purpose is to get data from the keyboard and return a maybe value, 
saying "nothing" if the data entered is invalid.
I get  a message "could'nt match expected IO Integer against inferred 
type maybe integer" on line x<- getdata
Why should x be Maybe ? getdatanum is, but getdata is not.

Is it possible to write only one function rather than 2 distinct ones ?

Thanks for your help,
Didier.


Here's my code

getdata ::  IO Integer
getdata=do   
    x<-getLine
    let xn=read x ::Integer
    return xn

getdatanum :: Maybe Integer
getdatanum = do
    x <- getdata
    {-
    if x < 5
      then do
        return (Just x)
      else do
        return Nothing
    -}
    return (Just x)





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

Message: 4
Date: Mon, 28 Dec 2009 10:05:44 +1300
From: "Stephen Blackheath [to Haskell-Beginners]"
        <[email protected]>
Subject: Re: [Haskell-beginners] Maybe and IO
To: legajid <[email protected]>
Cc: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=UTF-8

Didier,

See below...

legajid wrote:
> Hi,
> My purpose is to get data from the keyboard and return a maybe value,
> saying "nothing" if the data entered is invalid.
> I get  a message "could'nt match expected IO Integer against inferred
> type maybe integer" on line x<- getdata
> Why should x be Maybe ? getdatanum is, but getdata is not.
> 
> Is it possible to write only one function rather than 2 distinct ones ?
> 
> Thanks for your help,
> Didier.
> 
> 
> Here's my code
> 
> getdata ::  IO Integer
> getdata=do      x<-getLine
>    let xn=read x ::Integer
>    return xn
> 
> getdatanum :: Maybe Integer
> getdatanum = do
>    x <- getdata
>    {-
>    if x < 5
>      then do
>        return (Just x)
>      else do
>        return Nothing
>    -}
>    return (Just x)

The type of getdatanum should be IO (Maybe Integer).  Maybe and IO are
both monads, and that's why the error messages can be a bit confusing
sometimes.

Yes, you certainly can write this as one function.


Steve


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

Message: 5
Date: Sun, 27 Dec 2009 16:24:42 -0500
From: Brent Yorgey <[email protected]>
Subject: Re: [Haskell-beginners] Enumerated types
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=us-ascii

On Sun, Dec 27, 2009 at 06:17:34PM +0100, legajid wrote:
> Thanks.
>
> for 1, i tried mapM ( putStrLn) (show pref) but show  gives only one line 
> with all values, instead of n lines with 1 value. I now understand that 
> show must be in the function that is mapped.

Right, pref is a list so (show pref) will just give you a String
representing the entire list.  You can do (map show pref) to give you
a list of Strings, one for each value.  So you could write

  mapM_ putStrLn (map show pref)

which is actually equivalent to

  mapM_ (putStrLn . show) pref

-Brent


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

Message: 6
Date: Sun, 27 Dec 2009 23:13:48 +0000
From: Tom Davie <[email protected]>
Subject: Re: [Haskell-beginners] Enumerated types
To: legajid <[email protected]>
Cc: [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset="windows-1252"

To add to what the other guys have said, I'd like to comment on style..

re 1 (disp_pref), it's much more compositional to split that function into
two parts:

the pure part: showPrefs = unlines . map show $ pref
and the non pure part: putStrLn

The reason that this is better is that a future function can manipulate the
String that showPrefs produces – it can append, it can drop characters from
it, it can reverse it, etc... This is not true of what is left over after
the action of printing the string has happened.

It lets you reuse that function *much* more.

Bob

On Sun, Dec 27, 2009 at 1:42 PM, legajid <[email protected]> wrote:

> Hello,
>
> I have some trouble evaluating Enum class.
> Following is my source:
>
> data Authors= Buzzati | Werber | Verne | Ray | Asimov | Voltaire deriving
> (Enum, Show)
>
> auths=[Buzzati .. Verne] ++ enumFrom Ray
> pref=take 3 auths
> -- 1 disp_pref=mapM_ (putStrLn) pref
>
> auth1 = Buzzati
> auth2 = succ auth1       -- Werber
> auth3 = pred Asimov      -- Ray
> num_auth4=fromEnum Verne -- 2
> -- 2 toEnum
>
> main= display Buzzati
> display x = do
>       putStrLn (show x)
>       display (succ x)
> -- 3 end of enum
>
> 1. could'nt match expected type [Char] against inferred type Authors
> I would like to display each data constructor name on one line , giving :
> Buzzati
> Werber
> Verne
> How can i translate data from one type to another (Authors to [Char])?
>
> 2. Like fromEnum gives data constructor index, is it possible with toEnum
> (or other way) to get the nth constructor of the given type ?
> eg : 2 applied to Authors (not in scope ?) would give Verne
>
> 3. tried to take  'succ' of last tag  in  enumeration
> How to detect the end of an enumeration ? Can i get the maxbound index ?
>
> Thanks,
> Didier.
>
>
>
> _______________________________________________
> Beginners mailing list
> [email protected]
> http://www.haskell.org/mailman/listinfo/beginners
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 
http://www.haskell.org/pipermail/beginners/attachments/20091227/07a6a65f/attachment-0001.html

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

Message: 7
Date: Mon, 28 Dec 2009 03:19:58 +0000
From: Jon Harrop <[email protected]>
Subject: Re: [Haskell-beginners] Performance of parallel mergesort
To: "Stephen Blackheath [to Haskell-Beginners]"
        <[email protected]>,
        [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain;  charset="utf-8"

On Sunday 27 December 2009 20:56:51 you wrote:
> Jon Harrop wrote:
> > This is something that concerns me. Lots of discussions of parallelism,
> > including the Haskell literature I have read, neglect this critical
> > problem
> > of making sure that more time is spent doing useful work than spawning
> > tasks
> > (sparks). How is this solved in Haskell? Do you just put magic numbers in
> > that work on the machine you're currently using?
>
> It is simply not true that Haskell literature neglects the question of
> spark granularity - this is very basic and is always covered. Read 
> "Real World Haskell" (available free online).  There's no 'magic
> number'. You must explicitly write your code to give the right granule 
> size.

There is no "right granule" size. That's the whole point: the optimum is a 
function of the machine. If you hardcode the granularity then your code isn't 
future proof and isn't portable.

>From chapter 24 of Real World Haskell on sorting:

  "At this fine granularity, the cost of using par outweighs any possible 
usefulness. To reduce this effect, we switch to our non-parallel sort after 
passing some threshold."

>From the Sorting.hs file, parSort2 accepts a threshold "d":

  parSort2 :: (Ord a) => Int -> [a] -> [a]
  parSort2 d list@(x:xs)
    | d <= 0     = sort list
    | otherwise = force greater `par` (force lesser `pseq`
                                      (lesser ++ x:greater))
        where lesser      = parSort2 d' [y | y <- xs, y <  x]
              greater     = parSort2 d' [y | y <- xs, y >= x]
              d' = d - 1
  parSort2 _ _              = []

>From the SortMain.hs file, it is always invoked with the magic number "2":

  testFunction = parSort2 2

Moreover, their approach of subdividing a fixed number of times is suboptimal 
because it inhibits load balancing.

Later, about parallelized IO, they give the code:

  chunkedReadWith :: (NFData a) =>
                    ([LB.ByteString] -> a) -> FilePath -> IO a
  chunkedReadWith func path =
      withChunks (lineChunks (numCapabilities * 4)) func path

where "4" is one magic number that gets multiplied by the magic number the 
user supplied via the +RTS -N<n> command-line option.

They make no attempt to adapt the granularity to the machine at all and rely 
entirely upon magic numbers. Consequently, their parallel sort that got a 25% 
speedup on two cores achieves a 30% slowdown on my 8 core.

> I don't know the exact cost of sparking, but in my experience it 
> is quite small - so - as long as your granule is doing *some* real work,
> it should speed up.

Can you quantify it, e.g. How many FLOPS?

> Jon Harrop wrote:
> > The parallelism is obviously not obtaining any real speedup so something
> > is wrong. But can anyone fix it?
>
> I've spent a bit of time measuring parallel speedup on real commercial
> projects, and this is what I've found:
>
> 1. ghc-6.12 performs significantly better than ghc-6.10, and has now
> been released, therefore don't use ghc-6.10.

Ok.

> 2. The defaults generally work better than giving huge heap sizes.  Your
> -K100000000 - maximum heap size per thread - will either do nothing or
> cause an artificial slowdown (I have observed this with the minimum heap
> size option).  Don't use it, unless experimentation proves it makes
> things better.

On the contrary, the Haskell program dies without it:

$ time ./mergesort +RTS -N8
Stack space overflow: current size 8388608 bytes.
Use `+RTS -Ksize' to increase it.
[1]+  Done                    kwrite mergesort.hs

real    0m33.320s
user    3m29.397s
sys     0m0.592s

I had to add that -K command line option just to get the program to run to 
completion.

> 3. +RTS -s is well worth using. It breaks the time down into MUT
> (mutator) and GC (garbage collector).

Its says 78.5% GC time (with GHC 6.10).

> 4. MUT parallelization is excellent, but the parallel GC is not so good.
>  If your code is GC-heavy it can spend around half of its time garbage
> collecting, which doesn't parallelize so well, and this eats into the
> speedup.

Ok.

> 5. There seems to be a scalability problem with the parallel gc for
> larger numbers of cores (namely 8).  I am guessing somewhat, but my
> experiments tend to confirm the issue raised in Simon Marlow's (the
> implementor of GHC parallelization) recent paper that it's to do with
> "stopping the world" for gc.

Do you mean this bug:

  http://hackage.haskell.org/trac/ghc/ticket/3553

> If GHC's lack of perfection at this point in time makes Haskell "look
> bad" I don't mind.  I am not selling anything, so the reader at least
> knows they're getting the truth.  I see this as one of the great
> advantages of open source.

I'm sure we'd all rather see speedups. :-)

> Progress on GHC has been very rapid in the last couple of years, and so
> I know we'll continue to see the speed of GHC's parallelism improving in
> leaps and bounds.  It's actually still quite a new area, considering the
> difficulty of some of the technical issues and how recent it is that
> multicores are widely available on consumer hardware.

My original intent was to test a claim someone made: that mergesort in Haskell 
is competitively performant and trivially parallelized.

> I know you OCaml/F# guys are making great progress too.

F# is production ready but OCaml is dead in the water when it comes to 
multicore. I'm working on an OCaml replacement called HLVM but it is early 
days yet.

-- 
Dr Jon Harrop, Flying Frog Consultancy Ltd.
http://www.ffconsultancy.com/?e


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

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


End of Beginners Digest, Vol 18, Issue 28
*****************************************

Reply via email to