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:  one more step backwards (Felipe Lessa)
   2. Re:  one more step backwards (Stephen Tetley)
   3. Re:  Performance of Idiomatic lazy Haskell (Daniel Fischer)
   4. Re:  Performance of Idiomatic lazy Haskell (Markus B?hm)
   5.  foldl' vs seq (Gabi)
   6.  foldl' vs seq (Gabi)
   7. Re:  foldl' vs seq (Stephen Tetley)
   8.  foldl' vs seq (Gabi)
   9.  problem with hsc2hs (Jose A. Ortega Ruiz)


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

Message: 1
Date: Sun, 31 Jan 2010 17:53:01 -0200
From: Felipe Lessa <[email protected]>
Subject: Re: [Haskell-beginners] one more step backwards
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=us-ascii

(This e-mail is literate Haskell source code.)

On Sun, Jan 31, 2010 at 06:52:33PM +0000, Stephen Tetley wrote:
] In this case a simple stack tracking the expression as it is reduced
] should work, the code below isn't entirely correct as it seems to need
] 'r' input twice to do the first roll-back, but it is along the right
] lines.
]
] The function 'evaluate' has been split to pass the stack into the
] function 'evalWithStack' which does the recursive work.

Along these lines we may also change evalStep using the Writer
monad.

> import Control.Monad.Writer

> data Expression = Val Integer
>                 | Add Expression Expression
>                 | Subtract Expression Expression
>                 | Multiply Expression Expression
>                 | Divide Expression Expression
>          deriving Show
>
> demo1 = (Add(Add(Add(Add(Val 6)(Val 5))(Val 10))(Val 7))(Val 30))

Some utilities:

> -- | Applying a function to two Val's.
> val :: BinOp Integer -> BinOp Expression
> val (#) (Val a) (Val b) = Val (a # b)
>
> type BinOp a = a -> a -> a

We can use the same type stack of expressions as before.

> type Stack = [Expression]

Our monad is a writer of stacks:

> type Evaluation a = Writer Stack a

The idea is to 'tell' each step of the evaluation.

> step :: Expression -> Evaluation Expression
> step x = tell [x] >> return x

If there's nothing to do we just return the value.  We don't
'tell' because we didn't evaluate anything.  With an Add we
recursively evaluate the operands.  If they 'tell' anything then
we modify their expression to include ourselves with 'censor'.

> evalStep' :: Expression -> Evaluation Expression
> evalStep' (Val x)   = return (Val x)
> evalStep' (Add x y) = do
>   x' <- censor (map (\k -> Add k  y)) (evalStep' x)
>   y' <- censor (map (\k -> Add x' k)) (evalStep' y)
>   step (val (+) x' y')

In fact, that pattern may be abstracted way

> evalBinOp :: BinOp Integer -> BinOp Expression
>           -> (Expression -> Expression -> Evaluation Expression)
> evalBinOp (#) mkOp x y = do
>   x' <- censor (map (\k -> mkOp k  y)) (evalStep x)
>   y' <- censor (map (\k -> mkOp x' k)) (evalStep y)
>   step (val (#) x' y')
>
> evalStep :: Expression -> Evaluation Expression
> evalStep (Val x)        = return (Val x)
> evalStep (Add x y)      = evalBinOp (+) Add x y
> evalStep (Subtract x y) = evalBinOp (-) Subtract x y
> evalStep (Multiply x y) = evalBinOp (*) Multiply x y
> evalStep (Divide x y)   = evalBinOp div Divide x y

However we'll generate all expressions lazily at once

> evaluate :: Expression -> Stack
> evaluate expr = expr : execWriter (evalStep expr)

Now you just have to walk lazily through the list :).  This is
the job of a zipper, which I'll briefly reconstruct here.

> data Zipper a = Zipper [a] a [a]
>
> fromList (x:xs) = Zipper [] x xs
> focus (Zipper _ x _) = x
>
> left z@(Zipper [] _ _)     = z
> left (Zipper (l:ls) x rs)  = Zipper ls l (x:rs)
>
> right z@(Zipper _ _ [])    = z
> right (Zipper ls x (r:rs)) = Zipper (x:ls) r rs

And then the "boring" IO part:

> interactive :: Expression -> IO ()
> interactive = go . fromList . evaluate
>   where go z = do putStrLn $ "Result is " ++ show (focus z)
>                   putStrLn "Do another step (y/n) or rollback (r)?"
>                   c <- getLine
>                   case c of
>                     "y" -> go (right z)
>                     "r" -> go (left z)
>                     _   -> putStrLn "Sayonara!"

Of course you could also see if we are on one of the ends of the
zipper to tell the user he cannot step or rollback.

Hope that helps,

--
Felipe.


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

Message: 2
Date: Sun, 31 Jan 2010 20:22:41 +0000
From: Stephen Tetley <[email protected]>
Subject: Re: [Haskell-beginners] one more step backwards
Cc: [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1

On 31 January 2010 19:53, Felipe Lessa <[email protected]> wrote:

> Along these lines we may also change evalStep using the Writer
> monad.

Hi Felipe - nice!

Bill Harrison lists DebugT (equipped with the non-proper morphism
'rollback') as one of the monad transformers in his periodic table of
effects:

http://www.cs.missouri.edu/~harrisonwl/Presentations/UIUCFM05.ppt

I've been curious since first seeing the slides, how an implementation
might efficiently store the state...

Best wishes

Stephen


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

Message: 3
Date: Sun, 31 Jan 2010 21:43:12 +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 20:22:56 schrieb Stephen Tetley:
> On my machine, they diverged at the eighth decimal place -
>
> Leibniz4 3.1415926526069526
> Leibniz1 3.1415926445727678

Ah, that. I thought you were talking about timings.

There are several things that can lead to differing results here,

1) order of summation (I think only my loop had a different order)
2) due to different tests, it might happen that one algorithm evaluates one 
term more than the other
3) are intermediate results truncated to 64 bits or kept in an 80-bit 
register?

I'm astonished by the size of the difference, though.

But if you sum from small to large, the results are very accurately the 
theoretically expected results, so I think it's 1) together with 3) which 
make the difference.


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

Message: 4
Date: Mon, 1 Feb 2010 10:37:41 +0100
From: Markus B?hm <[email protected]>
Subject: Re: [Haskell-beginners] Performance of Idiomatic lazy Haskell
To: Daniel Fischer <[email protected]>
Cc: [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1

Daniel, Stephen, Felipe thanks for Your answers/advice, which I
studied this morning. Helps me a lot on my learning curve. I guess it
takes some time to get a feeling for the performance/runtime behaviour
of abstractions in Haskell.

Just for fun and w/o knowing Lua: I translated my Haskell
"loops-while"-version into Lua and ran on LuaJit Beta 2.0.0. Seems to
beat our best Haskell version.

print("EPS: ")
EPS = io.read("*number")
pi2 = 1
i = 3
s = false
repeat
    pi1 = pi2
    if s then
        pi2 = pi1 + 1.0/i
        s = false
    else
        pi2 = pi1 - 1.0/i
        s = true
    end
    i = i+2

until EPS > 4.0 * math.abs(pi2-pi1)

print("PI mit EPS", EPS," = ",4*pi1," n= ",(i-3)/2)


-- Markus




On Sun, Jan 31, 2010 at 9:43 PM, Daniel Fischer
<[email protected]> wrote:
> Am Sonntag 31 Januar 2010 20:22:56 schrieb Stephen Tetley:
>> On my machine, they diverged at the eighth decimal place -
>>
>> Leibniz4 3.1415926526069526
>> Leibniz1 3.1415926445727678
>
> Ah, that. I thought you were talking about timings.
>
> There are several things that can lead to differing results here,
>
> 1) order of summation (I think only my loop had a different order)
> 2) due to different tests, it might happen that one algorithm evaluates one
> term more than the other
> 3) are intermediate results truncated to 64 bits or kept in an 80-bit
> register?
>
> I'm astonished by the size of the difference, though.
>
> But if you sum from small to large, the results are very accurately the
> theoretically expected results, so I think it's 1) together with 3) which
> make the difference.
> _______________________________________________
> Beginners mailing list
> [email protected]
> http://www.haskell.org/mailman/listinfo/beginners
>


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

Message: 5
Date: Mon, 1 Feb 2010 12:34:32 +0200
From: Gabi <[email protected]>
Subject: [Haskell-beginners] foldl' vs seq
To: [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1

Hi
I am trying to understand the behavior of foldl' and seq.
Why is the following code is much slower than the foldl' version ?
(which is foldl' (+)  0)
I thought the the below code is equivalent to foldr' but apparently I was wrong.

mySum :: [Integer] -> Integer
mySum[] = 0
mySum (x:xs) = seq x (mySum xs + x)


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

Message: 6
Date: Mon, 1 Feb 2010 13:05:23 +0200
From: Gabi <[email protected]>
Subject: [Haskell-beginners] foldl' vs seq
To: [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1

Update: I came up with the following somewhat faster function. But
still, it is much slower than the original foldl'

mySum2  (x:y:xs) = let sum = x + y
              in seq sum (sum + mySum2 xs)
mySum2 (x:[]) = x
mySum2 [] = 0


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

Message: 7
Date: Mon, 1 Feb 2010 11:31:33 +0000
From: Stephen Tetley <[email protected]>
Subject: Re: [Haskell-beginners] foldl' vs seq
To: Gabi <[email protected]>
Cc: [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1

Hi Gabi

The seq is not forcing the strictness that you are expecting.

A tail recursive accumulator version is comparable to foldl' (I'm not
sure which other pieces out of the bag of strictness tricks deepseq,
etc would get the same results without the accumulator).

Best wishes

Stephen


All versions compiled with -O2...

module Main where


mySum :: [Integer] -> Integer
mySum xs0 = step 0 xs0 where
  step a []     = a
  step a (x:xs) = let a' = a+x in a' `seq` step a' xs

main = do
  putStrLn "mySum tail-rec:"
  putStrLn $ "mySum [1..10^6]:" ++ show (mySum [1..10^6])

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

$ ./MySumTR.exe +RTS -sstderr -RTS
d:\coding\haskell\cafe\MySumTR.exe +RTS -sstderr
mySum tail-rec:
mySum [1..10^6]:500000500000
     100,439,096 bytes allocated in the heap
          16,572 bytes copied during GC
           3,276 bytes maximum residency (1 sample(s))
          11,944 bytes maximum slop
               1 MB total memory in use (0 MB lost due to fragmentation)

  Generation 0:   192 collections,     0 parallel,  0.00s,  0.00s elapsed
  Generation 1:     1 collections,     0 parallel,  0.00s,  0.00s elapsed

  INIT  time    0.02s  (  0.00s elapsed)
  MUT   time    0.33s  (  0.33s elapsed)
  GC    time    0.00s  (  0.00s elapsed)
  EXIT  time    0.00s  (  0.00s elapsed)
  Total time    0.34s  (  0.33s elapsed)

  %GC time       0.0%  (0.0% elapsed)

  Alloc rate    292,186,461 bytes per MUT second

  Productivity  95.5% of total user, 100.0% of total elapsed

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

$ ./SeqFoldl.exe +RTS -sstderr -RTS
d:\coding\haskell\cafe\SeqFoldl.exe +RTS -sstderr
sum (foldl'):
sum [1..10^6]:500000500000
     100,438,952 bytes allocated in the heap
          16,572 bytes copied during GC
           3,276 bytes maximum residency (1 sample(s))
          11,944 bytes maximum slop
               1 MB total memory in use (0 MB lost due to fragmentation)

  Generation 0:   192 collections,     0 parallel,  0.03s,  0.03s elapsed
  Generation 1:     1 collections,     0 parallel,  0.00s,  0.00s elapsed

  INIT  time    0.02s  (  0.00s elapsed)
  MUT   time    0.30s  (  0.30s elapsed)
  GC    time    0.03s  (  0.03s elapsed)
  EXIT  time    0.00s  (  0.00s elapsed)
  Total time    0.34s  (  0.33s elapsed)

  %GC time       9.1%  (9.5% elapsed)

  Alloc rate    321,404,646 bytes per MUT second

  Productivity  86.4% of total user, 90.5% of total elapsed


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

Message: 8
Date: Mon, 1 Feb 2010 13:54:31 +0200
From: Gabi <[email protected]>
Subject: [Haskell-beginners] foldl' vs seq
To: [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1

Hi Stephen,
Thanks for the answer. Now I got confused :)

1. What is seq used for if it doesn't force strictness ?
2. Why the accumulator is important ? In other words why the following
is much slower ? Isn't it RT too ?

slowSum :: [Integer] -> Integer
slowSum[] = 0
slowSum (x:xs) = x `seq` x + slowSum xs


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

Message: 9
Date: Mon, 01 Feb 2010 12:48:02 +0100
From: "Jose A. Ortega Ruiz" <[email protected]>
Subject: [Haskell-beginners] problem with hsc2hs
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=us-ascii


Hi,

I'm trying to writing a simple C binding for statfs(2). Simplifying,
writing an hsc file that contains the following snippet:

  #include <sys/vfs.h>

  data CStatfs
  foreign import ccall unsafe "sys/vfs.h statfs"
    c_statfs :: CString -> Ptr CStatfs -> IO CInt

  getFileSystemStats :: String -> IO CLong
  getFileSystemStats path =
    allocaBytes (#size struct statfs) $ \vfs ->
    useAsCString (pack path) $ \cpath -> do
      res <- c_statfs cpath vfs
      case res of
        -1 -> return 0
        _  -> do
          bsize <- (#peek struct statfs, f_bsize) vfs
          bcount <- (#peek struct statfs, f_blocks) vfs
          bfree <- (#peek struct statfs, f_bfree) vfs
          bavail <- (#peek struct statfs, f_bavail) vfs
          -- Just for demonstration: the original code creates a data structure
          return $ bsize + bcount + bavail + bfree

gives rise, when using hsc2hs, to this translation:

  getFileSystemStats path =
    allocaBytes ((84)) $ \vfs ->
    useAsCString (pack path) $ \cpath -> do
      res <- c_statfs cpath vfs
      case res of
        -1 -> return 0
        _  -> do
          bsize <- ((\hsc_ptr -> peekByteOff hsc_ptr 4)) vfs
          bcount <- ((\hsc_ptr -> peekByteOff hsc_ptr 8)) vfs
          bfree <- ((\hsc_ptr -> peekByteOff hsc_ptr 16)) vfs
          bavail <- ((\hsc_ptr -> peekByteOff hsc_ptr 24)) vfs
          return $ bsize + bcount + bavail + bfree

(where i have deleted LINE directives). The problem is that the size and
some of the offsets of the C struct statfs computed by hsc2c are wrong:
i'm in a 32bit linux system, and i've checked, using a C program, that
sizeof(struct statfs) is 64 (hsc2 is giving 84 -- although perhaps
Haskell needs additional space for housekeeping?), and that the offsets
of f_bfree and f_bavail are, respectively, 12 and 16 (not 16 and 24).
Also, i know that 12 and 16 are the right values because putting them by
hand gives me the correct statfs values.

(This is ghc 6.10.4 on a debian/sid system)

What am i doing wrong?

TIA!
jao



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

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


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

Reply via email to