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: Using Debug.Trace (Daniel Fischer)
2. Re: Performance of Idiomatic lazy Haskell (Felipe Lessa)
3. Re: Performance of Idiomatic lazy Haskell (Stephen Tetley)
4. Re: Performance of Idiomatic lazy Haskell (Stephen Tetley)
5. Re: Performance of Idiomatic lazy Haskell (Daniel Fischer)
6. Re: Performance of Idiomatic lazy Haskell (Stephen Tetley)
----------------------------------------------------------------------
Message: 1
Date: Sun, 31 Jan 2010 11:33:00 +0100
From: Daniel Fischer <[email protected]>
Subject: Re: [Haskell-beginners] Using Debug.Trace
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset="iso-8859-1"
Am Sonntag 31 Januar 2010 10:25:58 schrieb legajid:
> Hi,
>
> Starting with trace, i have trouble with my calcul'' function while
> calcul' is ok.
> When afftrace in calcul'' is commented, the program compiles.
> When uncommented ( afftrace (" calcul'' vide") ), i get
> the following messages :
>
> ------------------------------------------------------------------------
>------------------- *Main> :r
> [1 of 1] Compiling Main ( sud3c.hs, interpreted )
>
> sud3c.hs:62:3:
> Couldn't match expected type `[Char]'
> against inferred type `(Plateau, Char)'
> In a stmt of a 'do' expression: afftrace (" calcul'' vide")
> In the expression:
> do afftrace (" calcul'' vide")
> (pxv, False)
> In the definition of `calcul''':
> calcul'' pxv _ []
> = do afftrace (" calcul'' vide")
> (pxv, False)
> Failed, modules loaded: none.
> ------------------------------------------------------------------------
>-------------------
>
> I don't understand why, in calcul', it's ok and why, in calcul'', it's
> problematic. Because return value of calcul'' is a tuple ?
You defined
> afftrace x= if modetrace then trace x " "
> else " "
If you ask ghci the type of that, you'll get
ghci> :t afftrace
afftrace :: String -> [Char]
(or afftrace :: [Char] -> [Char], or String -> String)
since
ghci> :t trace
trace :: String -> a -> a
Now you use afftrace in a do-block, which means "afftrace x" must have type
(Monad m) => m a
for some m and a.
Well, afftrace x has type [Char], so m is [] and a is Char, fine.
That means you can use afftrace in any calculation returning a list of some
kind (outside of do-blocks, also in other calculations).
But calcul'' doesn't return a list, it returns a pair. So
calcul'' pxv _ [] = afftrace (" calcul'' vide") >> (pxv,False)
, which is what the first equation of calcul'' is desugared to, isn't well
typed.
(>>) :: Monad m => m a -> m b -> m b
afftrace " calcul'' vide" :: [] Char -- m === [], a === Char
(pxv,False) :: (,) Plateau Bool -- m === ((,) Plateau), b === Bool
(actually, ((,) Plateau) is indeed a monad, but it's a different one from
[], so the expression is not well typed).
You could
- modify calcul'' to return [(Plateau,Bool)]
- not use do-blocks just for the sake of tracing and restructure your code
(I recommend the second)
infixl 0 `debug`
debug = flip trace
calcul' pxv [] = pxv `debug` " Calcul' vide"
calcul' pxv (c:cs)
| ok1 = calcul' xv1 cs `debug` " Calcul' suite"
| otherwise = pxv `debug` " Calcul' pas de valeur"
where
vallib = [1 .. length pxv] ++ [5 .. 7]
nbvlib = length vallib
(xv1,ok1) = calcul'' pxv c vallib `debug` (" " ++ show xv1)
`debug` (" Calcul' ok1=" ++ show ok1 ++ "
c:cs= " ++ show (c:cs))
calcul'' pxv _ [] = (pxv,False) `debug` " calcul'' vide"
calcul'' pxv c (li:lis)
| False `debug` " " ++ show pvx ++ "..." = undefined
| li == 4 || li `elem` pxv = calcul'' pxv c lis `debug` "quoi?"
| otherwise = (calcul'' pxv c li,True) `debug` " calcul'''"
Now the code reads more natural (except for the "False `debug` ... " to
produce general debugging output), and removing the debugging output isn't
any harder.
>
> When my program is ok, should i remove all trace instructions (and
> associated do commands too) or just set my modetrace value to False ?
>
Remove, resp. comment out.
>
> Thanks for helping,
> Didier
>
> Below my code :
>
>
> calcul' :: Plateau -> [Cellule] -> Plateau
> calcul' pxv [] = do
> afftrace (" Calcul' vide")
> pxv
> calcul' pxv (c:cs)= do
> afftrace (" Calcul' ok1="++show ok1++" c:cs= "++show
> (c:cs)) afftrace (" "++show xv1)
>
> if ok1 then do
> afftrace (" Calcul' suite")
> calcul' xv1 cs
> else do
> afftrace (" Calcul' pas de valeur")
> pxv
> where
> vallib=[1..length pxv]++[5..7]
> nbvlib=length vallib
> (xv1,ok1)=calcul'' pxv c vallib
>
>
>
> calcul'' :: Plateau -> Cellule -> [Valeur] -> (Plateau, Bool)
> calcul'' pxv _ [] = do
> --afftrace (" calcul'' vide")
> (pxv, False)
>
> calcul'' pxv c (li : lis) = do
> --afftrace (" "++show pxv)
> --afftrace (" "++show c ++ " "++show(li:lis))
> v2
> where
> v2= if (elem li pxv || li==4)
> then
> calcul'' pxv c lis
> else do
> --afftrace (" calcul'''")
> (calcul''' pxv c li, True)
>
> calcul''' :: Plateau -> Cellule -> Valeur -> Plateau
> calcul''' pxv c li =
> take (c-1) pxv ++ [li] ++ drop c pxv
>
> afftrace x= if modetrace then trace x " "
> else " "
------------------------------
Message: 2
Date: Sun, 31 Jan 2010 09:28:44 -0200
From: Felipe Lessa <[email protected]>
Subject: Re: [Haskell-beginners] Performance of Idiomatic lazy Haskell
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=iso-8859-1
On Sun, Jan 31, 2010 at 11:14:36AM +0100, Markus Böhm wrote:
> Variant 1: My lazy, idiomatic approach (as I understand it so far).
> It takes on my machine with eps = 0.00000001 approx. 25 sec.
>
> Variant 2: My "C-style" approach achieving state via additonal
> function parameters.
> It takes on my machine with eps = 0.00000001 approx. 5 sec.
You could try the stream-fusion package on Hackage:
http://hackage.haskell.org/package/stream-fusion
It should give better performance on this kind of code since it
can see the loops through the lists. Don't forget to compile
with optimizations! :)
HTH,
--
Felipe.
------------------------------
Message: 3
Date: Sun, 31 Jan 2010 11:37:02 +0000
From: Stephen Tetley <[email protected]>
Subject: Re: [Haskell-beginners] Performance of Idiomatic lazy Haskell
Cc: [email protected]
Message-ID:
<[email protected]>
Content-Type: text/plain; charset=ISO-8859-1
Hi Markus
I haven't tested the efficiency, but an unfold seems natural /
idiomatic in this case. The Leibniz formula generates a list in the
first step then sums it. Generating a list is often a perfect fit for
an unfold. The code below seems quite close to the idea of the Leibniz
formula (add 2 to the denominator, flip the sign at each step), sum
and multiple by 4.
> import Data.List (unfoldr)
> leibniz n = (4 *) $ sum $ take n step
-- Note this unfoldr generates an infinite list (both cases produce
Just values) ...
> step :: [Double]
> step = unfoldr phi (True,1) where
> phi (sig,d) | sig == True = Just (1/d, (False,d+2))
> | otherwise = Just (negate (1/d), (True,d+2))
Alternatively, an unfoldr with a stop condition might seem more
natural, creating a bounded list. However, here it is a bit ugly
as there are now 3 elements in the unfold state:
> leibniz' n = (4 *) $ sum $ step' n
> step' :: Int -> [Double]
> step' n = unfoldr phi (0,True,1) where
> phi (i,_,_) | i == n = Nothing
> phi (i,sig,d) | sig == True = Just (1/d, (i+1,False,d+2))
> | otherwise = Just (negate (1/d), (i+1,True,d+2))
Best wishes
Stephen
------------------------------
Message: 4
Date: Sun, 31 Jan 2010 12:23:33 +0000
From: Stephen Tetley <[email protected]>
Subject: Re: [Haskell-beginners] Performance of Idiomatic lazy Haskell
Cc: [email protected]
Message-ID:
<[email protected]>
Content-Type: text/plain; charset=ISO-8859-1
Hi Markus
Whoops, I hadn't read your email properly and wasn't accounting for
the epsilon. Here's a version that does, although it is perhaps a
little slow...
> import Data.List (unfoldr)
> leibniz eps = converge eps ser
> ser :: [Double]
> ser = unfoldr phi (True,1) where
> phi (sig,d) | sig == True = Just (1/d, (False,d+2))
> | otherwise = Just (negate (1/d), (True,d+2))
> converge :: Double -> [Double] -> Double
> converge eps xs = step 0 0 xs where
> step a b (x:xs) = let a' = a + (4*x) in
> if abs (a'-b) < eps then a' else step a' a xs
> demo1 = leibniz 0.00000000025
Best wishes
Stephen
------------------------------
Message: 5
Date: Sun, 31 Jan 2010 14:39:56 +0100
From: Daniel Fischer <[email protected]>
Subject: Re: [Haskell-beginners] Performance of Idiomatic lazy Haskell
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset="iso-8859-1"
Am Sonntag 31 Januar 2010 13:23:33 schrieb Stephen Tetley:
> Hi Markus
>
> Whoops, I hadn't read your email properly and wasn't accounting for
> the epsilon. Here's a version that does, although it is perhaps a
> little slow...
>
Better use the previous and calculate how many terms you need:
============================================
module Main (main) where
import Data.List (unfoldr)
main :: IO ()
main = do
putStrLn "EPS: "
eps <- readLn :: IO Double
let mx = floor (4/eps)
!k = (mx+1) `quot` 2
putStrLn $ "PI mit EPS " ++ (show eps) ++ " = " ++ show (leibniz k)
leibniz n = (4 *) $ sum $ take n step
step :: [Double]
step = unfoldr phi (True,1) where
phi (sig,d) | sig = Just (1/d, (False,d+2))
| otherwise = Just (negate (1/d), (True,d+2))
giving
$ echo '0.00000001' | ./unfoldPi +RTS -sstderr -RTS
./unfoldPi +RTS -sstderr
EPS:
PI mit EPS 1.0e-8 = 3.141592648589476
27,305,969,616 bytes allocated in the heap
2,523,788 bytes copied during GC
61,660 bytes maximum residency (1 sample(s))
38,864 bytes maximum slop
1 MB total memory in use (0 MB lost due to fragmentation)
Generation 0: 52083 collections, 0 parallel, 0.29s, 0.44s elapsed
Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s elapsed
INIT time 0.00s ( 0.00s elapsed)
MUT time 23.10s ( 23.14s elapsed)
GC time 0.29s ( 0.44s elapsed)
EXIT time 0.00s ( 0.00s elapsed)
Total time 23.39s ( 23.57s elapsed)
%GC time 1.2% (1.9% elapsed)
Alloc rate 1,182,002,769 bytes per MUT second
Productivity 98.8% of total user, 98.0% of total elapsed
===============================================
a little better if we do the unfolding ourselves, not creating any
intermediate pairs:
leibniz n = (4*) . sum $ unf n True 1
unf :: Int -> Bool -> Double -> [Double]
unf 0 _ _ = []
unf k True n = 1/n : unf (k-1) False (n+2)
unf k False n = negate (1/n) : unf (k-1) True (n+2)
which gives
$ echo '0.00000001' | ./unfPi +RTS -sstderr -RTS
./unfPi +RTS -sstderr
EPS:
PI mit EPS 1.0e-8 = 3.141592648589476
15,250,801,168 bytes allocated in the heap
1,284,632 bytes copied during GC
61,592 bytes maximum residency (1 sample(s))
38,864 bytes maximum slop
1 MB total memory in use (0 MB lost due to fragmentation)
Generation 0: 29089 collections, 0 parallel, 0.22s, 0.32s elapsed
Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s elapsed
INIT time 0.00s ( 0.00s elapsed)
MUT time 18.05s ( 18.05s elapsed)
GC time 0.22s ( 0.32s elapsed)
EXIT time 0.00s ( 0.00s elapsed)
Total time 18.28s ( 18.37s elapsed)
%GC time 1.2% (1.7% elapsed)
Alloc rate 844,773,242 bytes per MUT second
Productivity 98.8% of total user, 98.2% of total elapsed
=============================================
Still not competitive with the loop version
$ echo '0.00000001' | ./loopPi +RTS -sstderr -RTS
./loopPi +RTS -sstderr
EPS:
PI mit EPS 1.0e-8 = 3.1415926526069526
136,248 bytes allocated in the heap
2,024 bytes copied during GC
51,720 bytes maximum residency (1 sample(s))
38,392 bytes maximum slop
1 MB total memory in use (0 MB lost due to fragmentation)
Generation 0: 0 collections, 0 parallel, 0.00s, 0.00s elapsed
Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s elapsed
INIT time 0.00s ( 0.00s elapsed)
MUT time 6.64s ( 6.64s elapsed)
GC time 0.00s ( 0.00s elapsed)
EXIT time 0.00s ( 0.00s elapsed)
Total time 6.64s ( 6.64s elapsed)
%GC time 0.0% (0.0% elapsed)
Alloc rate 20,517 bytes per MUT second
Productivity 100.0% of total user, 100.0% of total elapsed
which can also be improved:
{-# LANGUAGE BangPatterns #-}
module Main (main) where
main :: IO ()
main = do
putStrLn "EPS: "
eps <- readLn :: IO Double
let mx = floor (4/eps)
k = (mx-1) `quot` 2
!pi14 = pisum (even k) (fromInteger (2*k+1))
putStrLn $ "PI mit EPS "++(show eps)++" = "++ show(4*pi14)
-- sum from small numbers to large, to reduce cancellation
-- although, in this particular case, for eps = 1e-8, the result is
-- farther off than summing the other way
pisum :: Bool -> Double -> Double
pisum bl start = go bl start 0
where
go _ n s | n < 1 = s
go True n !s = go False (n-2) (s+recip n)
go False n !s = go True (n-2) (s-recip n)
$ echo '0.00000001' | ./mloopPi +RTS -sstderr -RTS
./mloopPi +RTS -sstderr
EPS:
PI mit EPS 1.0e-8 = 3.141592648589793
136,416 bytes allocated in the heap
2,024 bytes copied during GC
51,720 bytes maximum residency (1 sample(s))
38,392 bytes maximum slop
1 MB total memory in use (0 MB lost due to fragmentation)
Generation 0: 0 collections, 0 parallel, 0.00s, 0.00s elapsed
Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s elapsed
INIT time 0.00s ( 0.00s elapsed)
MUT time 4.55s ( 4.56s elapsed)
GC time 0.00s ( 0.00s elapsed)
EXIT time 0.00s ( 0.00s elapsed)
Total time 4.55s ( 4.56s elapsed)
%GC time 0.0% (0.0% elapsed)
Alloc rate 29,966 bytes per MUT second
Productivity 99.9% of total user, 99.8% of total elapsed
Most of the gain is due to the much simpler loop-break test, a small bit
may be due to bang-patterns vs. seq.
Bottom line:
GHC isn't very good at fusing away intermediate lists in strict algorithms
(it's better at it for lazy algorithms). Allocating so many cons-cells just
to be immediately garbage-collected costs a lot of time.
You can code the loop directly, which gives reasonable results, or, as
Felipe suggested, use the fusion framework created by experts:
module Main (main) where
import qualified Data.List.Stream as S
main :: IO ()
main = do
putStrLn "EPS: "
eps <- readLn :: IO Double
let mx = floor (4/eps)
!k = (mx+1) `quot` 2
putStrLn $ "PI mit EPS " ++ (show eps) ++ " = " ++ show (leibniz k)
leibniz n = (4 *) $ S.sum $ S.take n step
step :: [Double]
step = S.unfoldr phi (True,1) where
phi (sig,d) | sig = Just (1/d, (False,d+2))
| otherwise = Just (negate (1/d), (True,d+2))
which beats the hand-coded loop:
$ echo '0.00000001' | ./sunfPi +RTS -sstderr -RTS
./sunfPi +RTS -sstderr
EPS:
PI mit EPS 1.0e-8 = 3.1415926445727678
136,560 bytes allocated in the heap
2,024 bytes copied during GC
51,720 bytes maximum residency (1 sample(s))
38,392 bytes maximum slop
1 MB total memory in use (0 MB lost due to fragmentation)
Generation 0: 0 collections, 0 parallel, 0.00s, 0.00s elapsed
Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s elapsed
INIT time 0.00s ( 0.00s elapsed)
MUT time 4.27s ( 4.27s elapsed)
GC time 0.00s ( 0.00s elapsed)
EXIT time 0.00s ( 0.00s elapsed)
Total time 4.27s ( 4.27s elapsed)
%GC time 0.0% (0.0% elapsed)
Alloc rate 31,994 bytes per MUT second
Productivity 100.0% of total user, 100.0% of total elapsed
> > import Data.List (unfoldr)
> >
> >
> > leibniz eps = converge eps ser
> >
> >
> > ser :: [Double]
> > ser = unfoldr phi (True,1) where
> > phi (sig,d) | sig == True = Just (1/d, (False,d+2))
> >
> > | otherwise = Just (negate (1/d), (True,d+2))
> >
> > converge :: Double -> [Double] -> Double
> > converge eps xs = step 0 0 xs where
> > step a b (x:xs) = let a' = a + (4*x) in
> > if abs (a'-b) < eps then a' else step a' a xs
> >
> > demo1 = leibniz 0.00000000025
>
> Best wishes
>
> Stephen
------------------------------
Message: 6
Date: Sun, 31 Jan 2010 14:52:41 +0000
From: Stephen Tetley <[email protected]>
Subject: Re: [Haskell-beginners] Performance of Idiomatic lazy Haskell
Cc: [email protected]
Message-ID:
<[email protected]>
Content-Type: text/plain; charset=ISO-8859-1
Hi Daniel
Thanks - the figures are very impressive for the stream fusion
library. I knew the paper, but I hadn't looked at it the
implementation.
Making a stricter unfoldr by using a strictness annotation on the
state and getting rid of the tuple is nowhere near stream fusion-lib,
i.e:
data Maybe2 a st = Nothing2 | Just2 a !st
deriving (Eq,Show)
Performance wise stream fusion even beats a monoidal unfoldr. A
monoidal unfoldr seems reasonable to me for this problem as there is
no need to generate a list. As a monoidal unfoldr is not in the
'standard' libraries some people might not consider it idiomatic
though.
I put in a fixed value for epsilon in all three version rather than
used echo at the command line and compiled all with ghc --make -O2
--------------
module Main (main) where
import Data.Monoid
data Maybe2 a st = Nothing2 | Just2 a !st
deriving (Eq,Show)
dummy_eps :: Double
dummy_eps = 0.00000001
main :: IO ()
main = do
putStrLn "EPS: "
eps <- return dummy_eps
let mx = floor (4/eps)
!k = (mx+1) `quot` 2
putStrLn $ "PI mit EPS " ++ (show eps) ++ " = " ++ show (leibniz k)
leibniz n = (4 *) $ getSum $ step n
step :: Integer -> Sum Double
step times = unfoldrMon phi (0,True,1) where
phi (i,_,_) | i == times = Nothing2
phi (i,sig,d) | sig = Just2 (Sum (1/d)) (i+1,False,d+2)
| otherwise = Just2 (Sum (negate (1/d))) (i+1,True,d+2)
unfoldrMon :: Monoid a => (b -> Maybe2 a b) -> b -> a
unfoldrMon f b =
case f b of
Just2 a new_b -> a `mappend` unfoldrMon f new_b
Nothing2 -> mempty
--
---------------------------------------------------
Leibniz1 (stream fusion)
---------------------------------------------------
$ ./Leibniz1 +RTS -sstderr -RTS
d:\coding\haskell\cafe\Leibniz1.exe +RTS -sstderr
EPS:
PI mit EPS 1.0e-8 = 3.1415926445727678
24,404 bytes allocated in the heap
892 bytes copied during GC
3,068 bytes maximum residency (1 sample(s))
13,316 bytes maximum slop
1 MB total memory in use (0 MB lost due to fragmentation)
Generation 0: 0 collections, 0 parallel, 0.00s, 0.00s elapsed
Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s elapsed
INIT time 0.03s ( 0.00s elapsed)
MUT time 4.59s ( 4.59s elapsed)
GC time 0.00s ( 0.00s elapsed)
EXIT time 0.00s ( 0.00s elapsed)
Total time 4.63s ( 4.59s elapsed)
%GC time 0.0% (0.0% elapsed)
Alloc rate 5,276 bytes per MUT second
Productivity 99.3% of total user, 100.0% of total elapsed
---------------------------------------------------
Leibniz3 (monoidal unfoldr)
---------------------------------------------------
$ ./Leibniz3 +RTS -sstderr -RTS
d:\coding\haskell\cafe\Leibniz3.exe +RTS -sstderr
EPS:
Stack space overflow: current size 8388608 bytes.
Use `+RTS -Ksize -RTS' to increase it.
92,448,984 bytes allocated in the heap
15,368 bytes copied during GC
8,382,800 bytes maximum residency (5 sample(s))
4,198,684 bytes maximum slop
17 MB total memory in use (0 MB lost due to fragmentation)
Generation 0: 125 collections, 0 parallel, 1.66s, 1.66s elapsed
Generation 1: 5 collections, 0 parallel, 0.03s, 0.03s elapsed
INIT time 0.03s ( 0.00s elapsed)
MUT time 3.50s ( 3.55s elapsed)
GC time 1.69s ( 1.69s elapsed)
EXIT time 0.00s ( 0.00s elapsed)
Total time 5.22s ( 5.23s elapsed)
%GC time 32.3% (32.2% elapsed)
Alloc rate 26,180,243 bytes per MUT second
Productivity 67.1% of total user, 66.9% of total elapsed
---------------------------------------------------
Leibniz2 - no stream fusion, unfoldr with strictness annotation on the state
---------------------------------------------------
$ ./Leibniz2 +RTS -sstderr -RTS
d:\coding\haskell\cafe\Leibniz2.exe +RTS -sstderr
EPS:
PI mit EPS 1.0e-8 = 3.141592648589476
25,600,024,064 bytes allocated in the heap
2,152,224 bytes copied during GC
3,336 bytes maximum residency (1 sample(s))
11,908 bytes maximum slop
1 MB total memory in use (0 MB lost due to fragmentation)
Generation 0: 48828 collections, 0 parallel, 2.19s, 2.23s elapsed
Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s elapsed
INIT time 0.02s ( 0.00s elapsed)
MUT time 75.16s ( 76.22s elapsed)
GC time 2.19s ( 2.23s elapsed)
EXIT time 0.00s ( 0.00s elapsed)
Total time 77.36s ( 78.45s elapsed)
%GC time 2.8% (2.8% elapsed)
Alloc rate 340,553,219 bytes per MUT second
Productivity 97.2% of total user, 95.8% of total elapsed
------------------------------
_______________________________________________
Beginners mailing list
[email protected]
http://www.haskell.org/mailman/listinfo/beginners
End of Beginners Digest, Vol 19, Issue 33
*****************************************