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:  Problems installing TagSoup.Parsec (Daniel Fischer)
   2. Re:  foldr for Nats (Stephen Tetley)
   3. Re:  Performance of Idiomatic lazy Haskell (Henk-Jan van Tuyl)
   4. Re:  one more step backwards (Felipe Lessa)
   5.  Re: foldl' vs seq (Ertugrul Soeylemez)
   6.  Re: foldl' vs seq (Gabi)


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

Message: 1
Date: Mon, 1 Feb 2010 21:42:14 +0100
From: Daniel Fischer <[email protected]>
Subject: Re: [Haskell-beginners] Problems installing TagSoup.Parsec
To: [email protected]
Cc: Mark Wong-VanHaren <[email protected]>
Message-ID: <[email protected]>
Content-Type: text/plain;  charset="utf-8"

Am Montag 01 Februar 2010 21:21:12 schrieb Mark Wong-VanHaren:
> Hi, folks-
>
> I'm a Haskell newbie.  There's a very real chance my question has a
> simple answer.

Yes and no. The problem is that the build-depends field of tagsoup-
parsec.cabal doesn't specify an upper bound on the version of tagsoup to 
use. Thus cabal tries to build it with the latest and greates tagsoup, 0.8.
Neill Mitchell changed the tagsoup API, bad .cabal files break.

Fix: unpack tagsoup-parsec-0.0.6, open the .cabal file, change


Library
   Build-Depends:  base<5, tagsoup, parsec<3

to

Library
   Build-Depends:  base<5, tagsoup < 0.7, parsec<3

$ cd tagsoup-parsec-0.0.6
$ cabal install

email maintainer of tagsoup-parsec to fix it (adapt to new tagsoup API).

>
> I wish to use the library Text.HTML.TagSoup.Parsec (
> http://hackage.haskell.org/package/tagsoup-parsec), which looks very
> cool.
>
> When I attempt to install it, I get this error:
>
> # cabal install tagsoup-parsec
> Resolving dependencies...
> Configuring tagsoup-parsec-0.0.6...
> Preprocessing library tagsoup-parsec-0.0.6...
> Building tagsoup-parsec-0.0.6...
> [1 of 1] Compiling Text.HTML.TagSoup.Parsec (
> Text/HTML/TagSoup/Parsec.hs, dist/build/Text/HTML/TagSoup/Parsec.o )
>
> Text/HTML/TagSoup/Parsec.hs:37:5:
>    `Tag' is not applied to enough type arguments
>    Expected kind `*', but `Tag' has kind `* -> *'
>    In the type synonym declaration for `WholeTag'
> cabal: Error: some packages failed to install:
> tagsoup-parsec-0.0.6 failed during the building phase. The exception
> was: exit: ExitFailure 1
>
>
> It would seem to be a type mismatch between TagSoup.Parsec and the base
> TagSoup (on which it depends).
>
> Suspecting that the version-number dependency information might be
> incorrect, I tried uninstalling TagSoup and reinstalling an older
> version. This didn't help.
>
> Can anyone steer me in the right direction?
>
> Thanks!
> -Mark



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

Message: 2
Date: Mon, 1 Feb 2010 21:56:14 +0000
From: Stephen Tetley <[email protected]>
Subject: Re: [Haskell-beginners] foldr for Nats
To: [email protected]
Cc: [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1

Hello

I'm suspecting this isn't homework as you've waited a week so would
presumably have missed a deadline.

As Daniel Fischer wrote, one view of folds is that they replace the
constructors of a data type, code follows...


data Nat = Z | S Nat   deriving (Eq,Ord,Show)


-- Look at the type of foldr...

-- *GHCi> :t foldr
-- foldr :: (a -> b -> b) -> b -> [a] -> b

-- It has 2 'constructor replacements':
-- (a -> b -> b) & b

-- Replacing Z is easy, we can get some code to compile
-- by avoiding the hard bit with a wildcard pattern "_"...

foldrNat1 :: unknown -> b -> Nat -> b
foldrNat1 _ b Z = b

-- What to do about the constructor (S ..) takes a bit more
-- thought or at least some experimenting. I'll do the later...

-- One thing to try, is to simply translate foldr with as few
-- changes as possible:

-- foldr            :: (a -> b -> b) -> b -> [a] -> b
-- foldr _ z []     =  z
-- foldr f z (x:xs) =  f x (foldr f z xs)

-- Unfortunately this leads to a problem:

foldrNat2 :: (Nat -> b -> b) -> b -> Nat -> b
foldrNat2 f b Z     = b     -- Z case is the same as before
foldrNat2 f b (S n) = f undefined (foldrNat2 f b n) -- Arggh! undefined

-- undefined is useful for prototyping, but its a real
-- problem for running code!

-- Actually I had another problem as well...
--
-- The difference between Nat and [a] is that List 'carries' some data
-- therefore (Nat -> b -> b) on Nat is not equivalent to (a -> b -> b)
-- on [a].

-- So rather than change the type signature first, get rid of the
-- undefined and see what happens

foldrNat3 f b Z     = b
foldrNat3 f b (S n) = f (foldrNat3 f b n)

-- *GHCi> :t foldrNat3
-- > (t -> t) -> t -> Nat -> t

-- GHCi likes to call type variables t, but the signature is equal to

-- foldrNat3 :: (b -> b) -> b -> Nat -> b


-- This looks promising - it typechecks!
-- So try a test:

fromNat :: Nat -> Int
fromNat n = foldrNat3 (+1) 0 n

demo1 = fromNat (S (S (S Z)))   -- 3 ??

-- By experimenting we seem to have a good answer,
-- other people might prefer a more rigorous proof though.


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

Message: 3
Date: Tue, 02 Feb 2010 00:05:58 +0100
From: "Henk-Jan van Tuyl" <[email protected]>
Subject: Re: [Haskell-beginners] Performance of Idiomatic lazy Haskell
To: "Tim Perry" <[email protected]>,  "Daniel Fischer"
        <[email protected]>, Markus B?hm <[email protected]>
Cc: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=iso-8859-15; format=flowed;
        delsp=yes


unxutils.zip seems to be gone; another option would be, to use MinGW/MSYS.  
You need this anyway for installing several Haskell packages that bind to  
C-software. If you start an MS-DOS shell and give command "sh", you are in  
a unixlike shell, where you can give the "time" command.

Regards,
Henk-Jan van Tuyl


--
http://Van.Tuyl.eu/
http://members.chello.nl/hjgtuyl/tourdemonad.html
--



On Mon, 01 Feb 2010 20:15:25 +0100, Tim Perry <[email protected]> wrote:

> CygWin would be a good option.
>
> Here are some other ideas:
>
> There is a timeit.exe utility in the Windows Server downloads which is  
> supposed to be similar to unix's time command. Try the links here
> http://channel9.msdn.com/forums/Coffeehouse/258979-Windows-equivalent-of-UnixLinux-time-command/
>
> Windows does support piping. It is similar to bash with 2>&1 to redirect  
> stderr to stdout and stuff.
> http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx?mfr=true
>
> The new windows shell is almost a real shell. Almost.
>
> If you don't have that, then this port of unix utilities makes an XP box  
> tolerable.
> http://unxutils.sourceforge.net/
>
> Hope that helps.
> --Tim
>
>
>
> ----- Original Message ----
> From: Daniel Fischer <[email protected]>
> To: Markus Böhm <[email protected]>
> Cc: [email protected]
> Sent: Mon, February 1, 2010 6:40:52 AM
> Subject: Re: [Haskell-beginners] Performance of Idiomatic lazy Haskell
>
> Am Montag 01 Februar 2010 15:22:45 schrieb Markus Böhm:
>
>> Daniel, I use GHC 6.12.1 and Windows XP.
>
> *sigh*
>
> Have you a CygWin installed? It should run as given from a CygWin shell,  
> I
> believe.
>
>> The time command doesn't seem
>> to work. It says in German: specified time can't be read. Give a new
>> time.
>
> Replace "time" with however you get the CPU time used by a process on
> Windows.
> But I think Windows doesn't allow piping, and I'm not sure whether it has
> echo, so see below.
>
>> Daniel, here another feedback:
>>
>> F:\MeineUebungen>ghc -O2 -fexcess-precision -fvia-C -optc-O3 -o luaLoop
>> --make p 085-pi_lualoop.hs
>> [1 of 1] Compiling Main             ( p085-pi_lualoop.hs,
>> p085-pi_lualoop.o ) Linking luaLoop.exe ...
>>
>> F:\MeineUebungen>echo '0.00000001' | time ./luaLoop
>> Eingegebene Zeit kann nicht übernommen werden.
>> Geben Sie die neue Zeit ein:
>>
>> F:\MeineUebungen>luaLoop +RTS -sstderr -RTS
>> luaLoop +RTS -sstderr
>> EPS:
>> 0.00000001
>> 3.1415926485894725
>>           61,428 bytes allocated in the heap
>>            1,316 bytes copied during GC
>>            4,564 bytes maximum residency (1 sample(s))
>>           11,820 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.02s  (  0.00s elapsed)
>>   MUT   time    8.06s  ( 16.83s elapsed)
>>   GC    time    0.00s  (  0.00s elapsed)
>>   EXIT  time    0.00s  (  0.00s elapsed)
>>   Total time    8.08s  ( 16.83s elapsed)
>>
>>   %GC time       0.0%  (0.0% elapsed)
>>
>>   Alloc rate    7,604 bytes per MUT second
>>
>>   Productivity  99.8% of total user, 47.9% of total elapsed
>
> What?????
>
> Please try the following:
>
> 1) hardcode eps = 1e-8 in the source (or get it via getArgs and pass it  
> as
> a command line argument)
> 2) ghc -O2 -fforce-recomp -fexcess-precision -fvia-C -optc-O3 -o cloop --
> make Source.hs
> 3) ghc -O2 -fforce-recomp -o nloop --make Source.hs
> 4) cloop +RTS -sstderr
> 5) nloop +RTS -sstderr
>
>>
>> -- Markus
>>
> _______________________________________________
> Beginners mailing list
> [email protected]
> http://www.haskell.org/mailman/listinfo/beginners
>
> _______________________________________________
> Beginners mailing list
> [email protected]
> http://www.haskell.org/mailman/listinfo/beginners


-- 


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

Message: 4
Date: Mon, 1 Feb 2010 21:37:37 -0200
From: Felipe Lessa <[email protected]>
Subject: Re: [Haskell-beginners] one more step backwards
To: John Moore <[email protected]>
Cc: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=us-ascii

On Mon, Feb 01, 2010 at 10:32:00PM +0000, John Moore wrote:
> Hi Felipe,
>               this is way complicated for my level, could you look at this
> below and see if I could use this instead.

I understand you, it also took me some time to understand the
monad transformer library :).

> evalStep :: Expression ->  Expression
> evalStep (Val x)=  (Val x)
> evalStep (Add x y)
>   = case x of
>       (Val a) -> case y of
>                    (Val b) -> Val (a+b)
>                    left -> Add x (evalStep y)
>       right -> Add (evalStep x)y

Even without the Writer monad you capture that pattern in an
auxiliary function.  You just extract the common bits and
abstract the specific ones:

  aux calcOp mkOp x y
     = case x of
         (Val a) -> case y of
                      (Val b) -> Val (a `calcOp` b)
                      left -> mkOp x (evalStep y)
         right -> mkOp (evalStep x) y

Note that:
 - I've changed (+) into calcOp and Add into mkOp.
 - Instead of deconstructing with a pattern match, I receive x
   and y as proper arguments.

The type is

  type CalcOp = Integer    -> Integer    -> Integer
  type MkOp   = Expression -> Expression -> Expression
  aux :: CalcOp -> MkOp -> Expression -> Expression
      -> (Expression -> Expression)

You can write your evalStep as

  evalStep :: Expression -> Expression
  evalStep (Val x)        = Val x
  evalStep (Add x y)      = aux (+) Add x y
  evalStep (Subtract x y) = aux (-) Subtract x y
  evalStep (Multiply x y) = aux (*) Multiply x y
  evalStep (Divide x y)   = aux div Divide x y

Much cleaner ;).

>   What I mean to do is build up a history on a list and then take it of a
> list( Same principle as a stack but a little more simple) the problem is how
> do I get the other elements back of the list as in the line "r" -> evaluate
> (I'm not sure what I put here) Hopes this makes some sort of sense.

It does makes sense.  In most languages this is the sort of code
you would write: when the user tell us to evaluate, we evaluate
and then save the result.  However in our language we can
leverage the laziness:

  buildHistory :: Expression -> [Expression]
  buildHistory expr = expr : buildHistory (evalStep)

You may recognize this function as

  buildHistory = iterate evalStep

(Note that unless your expression is infinite, then this list
will contain an infinite number of duplicates when we reach the
fixed point of the evalStep function.)

The idea is to take everything you can out of IO.  With
buildHistory we take the logic of evaluating the expressions
further out of IO.  Now your function is as trivial as mine.  In
fact, it is the same.

HTH,

--
Felipe.


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

Message: 5
Date: Tue, 2 Feb 2010 07:15:03 +0100
From: Ertugrul Soeylemez <[email protected]>
Subject: [Haskell-beginners] Re: foldl' vs seq
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=US-ASCII

Gabi <[email protected]> wrote:

> 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

Hello Gabi,

The seq function may not behave as you expect it to.  The following GHCi
session may help you understand this:

  Prelude> const 3 (seq undefined 0)
  3
  Prelude> snd (seq undefined 0, 1)
  1
  Prelude> fst (seq undefined 0, 1)
  *** Exception: Prelude.undefined

When the result of 'seq x y' is demanded, x is evaluated and then y is
returned as that result.  In the above session the first two expressions
never evaluate the seq call.  Haskell is lazy, so if you demand only the
second value of a tuple, the first one is never evaluated, even if it
contains 'seq x y'.  However, _if_ it is evaluated, it will evaluate x
first, then return y.

Your statement, x `seq` x + slowSum xs, can be rewritten in the
following way, seq x (x + slowSum xs), which makes clearer what it
means:  Upon evaluating x + slowSum xs, the value of x should be
evaluated.  In other words, your function builds the following result
thunk:

  slowSum [1,2,3] = 1 + 2 + 3 + 0

instead of:

  slowSum [1,2,3] = THUNK + THUNK + THUNK + 0

But it still builds a thunk, which will have to actually perform all the
additions.  Why?  Because nothing demands that sum until after all those
recursive calls return.  You are right in that a 'seq' is needed
somewhere, but not where you put it.  In fact the slowSum function
cannot be optimized any further, because it is not tail-recursive:

     slowSum [1,2,3]
  => 1 + slowSum [2,3]

Using prefix notation shows why the recursive call to slowSum is not the
last function call and hence is no tail recursion:

  (+) 1 (slowSum [2,3])

The problem of non-tail recursion is that the recursive calls have no
access to the "current result".  You cannot force the addition from
slowSum, because it's out of scope.

If you introduce an accumulation parameter, things change:

  fastSum :: Num a => a -> [a] -> a
  fastSum s []     = s
  fastSum s (x:xs) = fastSum (s+x) xs

Read it like:  'fastSum s xs' is the sum of the elements of xs plus the
value of s.  Reading it that way the code is self-explanatory, and
clearly it is tail-recursive, giving the function full access to the
current intermediary result (named s).  It builds the following result:

     fastSum 0 [1,2,3]
  => fastSum (0 + THUNK) [2,3]
  => fastSum (0 + THUNK + THUNK) [3]
  => fastSum (0 + THUNK + THUNK + THUNK) []
  => 0 + THUNK + THUNK + THUNK

Well, now it is tail-recursive, so it doesn't eat stack space anymore,
but it still builds that result expression instead of just giving the
end result.  This is where seq comes into play.  Now that you have
access to the intermediary result, you can force it to be evaluated
along the way:

  superFastSum :: Num a => a -> [a] -> a
  superFastSum s []     = s
  superFastSum s (x:xs) = s `seq` superFastSum (s+x) xs

Note how semantics have changed now:

     superFastSum 0 [1,2,3]
  => 0     `seq` superFastSum (0+1) [2,3]
  =>             superFastSum (0+1) [2,3]
  => (0+1) `seq` superFastSum ((0+1)+2) [3]
  =>             superFastSum (1+2) [3]
  => (1+2) `seq` superFastSum ((1+2)+3) []
  =>             superFastSum (3+3) []
  =>             3+3

The result of superFastSum on a non-empty list depends on a recursive
call to itself, but it clearly states (through seq) that _before_ that
call is evaluated, the value of s is evaluated.  So each time it
attempts to build a result expression, that expression is immediately
reduced to a value, to which the next list element is added.

The foldl' function can be used to encode such a recursion pattern
conveniently.  It's just like the superFastSum function, but takes an
arbitrary accumulation function instead of (+):

  import Data.List

  foldl' :: (a -> b -> a) -> a -> [b] -> a
  foldl' f z []     = z
  foldl' f z (x:xs) = z `seq` foldl' f (f z x) xs

  superFastSum     = foldl' (+) 0
  superFastProduct = foldl' (*) 1
  superFastLength  = foldl' (\x y -> x + 1) 0

I hope that helps.


Supplemental note #1:  Haskell compilers generally don't do common
subexpression elimination (CSE), because that may change language
semantics.  The following code will not behave as you may expect it to:

  f x `seq` print (f x)

With CSE in mind, you would expect the seq not to change anything and
just print the result, but this is wrong.  In fact it will be twice as
slow!  The reason is that to the compiler the first 'f x' is not the
same as the second 'f x'.  If you want them to be the same, you need to
make this explicit by giving them a common name:

  let y = f x in y `seq` print y

This is called memoizing and will work as expected, i.e. the seq will
not slow things down.  You can avoid some lets and wheres using the
strict function application operator:

  print $! f x


Supplemental note #2:  A better, memoizing foldl' implementation:

  foldl' :: (a -> b -> a) -> a -> [b] -> a
  foldl' f z []     = z
  foldl' f z (x:xs) =
    let r = f z x
    in r `seq` foldl' f r xs


Supplemental note #3:  I noticed that recent versions of GHC are smart
enough to know where it makes no semantic difference to force certain
calculations.  That means you can write the implementations of
superFastSum and foldl' without seq:

  superFastSumGHC = fastSum

  foldl' = foldl

However, for compatibility reasons you should still use seq.


Greets
Ertugrul


-- 
nightmare = unsafePerformIO (getWrongWife >>= sex)
http://blog.ertes.de/




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

Message: 6
Date: Tue, 2 Feb 2010 11:41:40 +0200
From: Gabi <[email protected]>
Subject: [Haskell-beginners] Re: foldl' vs seq
To: [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1

Thank you Ertugrul,

I think I got it now.
My lesson here is to avoid recursion as much possible and use foldr'
instead.There are too many pitfalls.



-- 
Regards,
Gabi

http://bugspy.net


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

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


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

Reply via email to