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. Applicative functors and trees (Darryn Reid)
2. Re: Applicative functors and trees (Maciej Piechotka)
3. Re: Memory usage problem (Sami Liedes)
4. Re: Memory usage problem (Henk-Jan van Tuyl)
5. Re: Applicative functors and trees (Brent Yorgey)
6. Re: Memory usage problem (Heinrich Apfelmus)
7. web (Dupont Corentin)
8. Re: web (Alex Rozenshteyn)
----------------------------------------------------------------------
Message: 1
Date: Mon, 22 Mar 2010 11:59:56 +1030
From: Darryn Reid <[email protected]>
Subject: [Haskell-beginners] Applicative functors and trees
To: [email protected]
Message-ID: <1269221396.2604.16.ca...@epicurus>
Content-Type: text/plain; charset="UTF-8"
Hi,
I'm playing around with Functors in Haskell with the aim of
understanding more structured functors, particularly applicative
functors and traversable and foldable. I'm using the standard binary
tree type to play around with this, as follows:
data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
I think I understand Functor fine:
instance Functor Tree where
fmap f Empty = Empty
fmap f (Leaf x) = Leaf (f x)
fmap f (Node l x r) = Branch (fmap f l) (f x) (fmap f r)
(with (<$>) being a synonym for fmap). This satisfies the laws for
Functor (I'll omit details). Likewise, I think I'm fine with Foldable,
for Tree a over any monoid a:
instance Foldable Tree
foldMap f Empty = mempty
foldMap f (Leaf x) = f x
foldMap f (Node l x r) = foldMap f l `mappend` f x `mappend`
foldMap f r
Where I'm stuck is with Applicative:
class (Functor f) => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
I understand that pure lifts a value into the applicative functor, so
this one is easy:
pure = Leaf
but I cannot see what <*> should look like. I know that <*> is
essentially application ($) lifted into the functor, so if the functor
were also a monad then <*> would be liftM2 ($), I suppose. But I want a
"direct" implementation, without monads floating about, but I cannot see
what to do.
I think then I would be able to define an instance for traversable as
something like this:
instance Traversable Tree
traverse f Empty = pure Empty
traverse f (Leaf x) = Leaf `fmap` f x
traverse f (Node l x r) = Node `fmap` traverse f (l <*> f x <*>
traverse f r)
(I think that <*> must be associative).
Can anyone advise what <*> should look like, please? Thanks in advance
for your help.
Darryn.
------------------------------
Message: 2
Date: Mon, 22 Mar 2010 02:18:41 +0000
From: Maciej Piechotka <[email protected]>
Subject: [Haskell-beginners] Re: Applicative functors and trees
To: [email protected]
Message-ID: <1269224320.5411.68.ca...@picard>
Content-Type: text/plain; charset="utf-8"
On Mon, 2010-03-22 at 11:59 +1030, Darryn Reid wrote:
> Where I'm stuck is with Applicative:
> class (Functor f) => Applicative f where
> pure :: a -> f a
> (<*>) :: f (a -> b) -> f a -> f b
>
> I understand that pure lifts a value into the applicative functor, so
> this one is easy:
> pure = Leaf
> but I cannot see what <*> should look like. I know that <*> is
> essentially application ($) lifted into the functor, so if the functor
> were also a monad then <*> would be liftM2 ($), I suppose. But I want
> a
> "direct" implementation, without monads floating about, but I cannot
> see
> what to do.
Hmm. When I played with trees I've done:
data Tree a = Leaf | Node (Tree a) a (Tree a)
instance Applicative Tree where
pure x = let t = Node t x t in t
-- if you prefer Node (pure x) x (pure x)
-- or fix (\t -> Node t x t)
Leaf <*> _ = Leaf
_ <*> Leaf = Leaf
(Node l f r) <*> (Node l' v r') =
Node (l <*> l') (f v) (r <*> r')
So maybe:
instance Applicative Tree where
pure x = let t = Node t x t in t
-- if you prefer Node (pure x) x (pure x)
Empty <*> _ = Empty
_ <*> Empty = Empty
(Leaf f) <*> (Leaf v) = Leaf (f v)
(Leaf f) <*> (Node _ v _) = Leaf (f v)
(Node _ f _) <*> (Leaf v) = Lead (f v)
(Node l f r) <*> (Node l' v r') =
Node (l <*> l') (f v) (r <*> r')
Both have unpleasant property of function returning infinite tree.
Regards
PS. Why do you need Leaf? How does Leaf x differ from (Node Empty x
Empty)?
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 836 bytes
Desc: This is a digitally signed message part
Url :
http://www.haskell.org/pipermail/beginners/attachments/20100321/cc410130/attachment-0001.bin
------------------------------
Message: 3
Date: Mon, 22 Mar 2010 21:58:29 +0200
From: Sami Liedes <[email protected]>
Subject: Re: [Haskell-beginners] Memory usage problem
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset="us-ascii"
On Mon, Mar 22, 2010 at 03:06:08AM +0200, Sami Liedes wrote:
> On Sun, Mar 21, 2010 at 08:28:23PM -0400, Patrick LeBoutillier wrote:
> > - Also, does memory usage improve if you remove the "sort"?
>
> Yes. Then it only takes a few megabytes, regardless of how large the
> file is.
This led me to investigate further. The following hack (and nothing
less crude I could invent) seems to significantly lessen the amount of
memory needed by the program. Now it takes maybe 180 megabytes instead
of 1.5 gigabytes. I guess the 180 megabytes consists of the output
stream (string), which is now explicitly computed entirely before
sorting and outputting it. It's still far from perfect.
I think there definitely _should_ be a better way of doing this
(forcing some computation to be strict so it takes less memory). Any
ideas? And I especially despise the (sum (map (const 0) b)) thing, but
it seems nothing less ugly does the trick.
It seems seq doesn't force the entire computation to finish, only the
next level. Is there some way to force the entire computation subtree
to finish? That way I could say just seq' b (if seq' was the function
that does that).
(see my original posting for the entire code)
------------------------------------------------------------
-- Return the unsorted package list and the sorted package list
processFile :: String -> (String,String)
processFile str =
let l = lines str
pkgs = readRecords l
in (unlines (map sprintPackage pkgs),
unlines (map sprintPackage (sort pkgs)))
-- Force the unsorted pkg list to be computed first (outputting it also
-- does the trick, but mere (map id b) doesn't). This is really ugly.
-- A mere "do putStrLn c" however eats 1.5 GB of memory instead of 180 MB.
main = do a <- getContents
let (b,c) = processFile a in
seq (sum (map (const 0) b)) (
do putStrLn c)
------------------------------------------------------------
Sami
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 836 bytes
Desc: Digital signature
Url :
http://www.haskell.org/pipermail/beginners/attachments/20100322/9db48cc7/attachment-0001.bin
------------------------------
Message: 4
Date: Mon, 22 Mar 2010 21:49:33 +0100
From: "Henk-Jan van Tuyl" <[email protected]>
Subject: Re: [Haskell-beginners] Memory usage problem
To: "Sami Liedes" <[email protected]>, [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=iso-8859-15; format=flowed;
delsp=yes
On Mon, 22 Mar 2010 20:58:29 +0100, Sami Liedes <[email protected]> wrote:
> It seems seq doesn't force the entire computation to finish, only the
> next level. Is there some way to force the entire computation subtree
> to finish? That way I could say just seq' b (if seq' was the function
> that does that).
>
You can use Control.Parallel.Strategies.rnf (Reduce to Normal Form) for
that.
Met vriendelijke groet,
Henk-Jan van Tuyl
--
http://Van.Tuyl.eu/
http://members.chello.nl/hjgtuyl/tourdemonad.html
--
------------------------------
Message: 5
Date: Tue, 23 Mar 2010 02:37:57 -0400
From: Brent Yorgey <[email protected]>
Subject: Re: [Haskell-beginners] Applicative functors and trees
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=us-ascii
On Mon, Mar 22, 2010 at 11:59:56AM +1030, Darryn Reid wrote:
> Hi,
>
> Where I'm stuck is with Applicative:
> class (Functor f) => Applicative f where
> pure :: a -> f a
> (<*>) :: f (a -> b) -> f a -> f b
I think there are actually lots of different Applicative instances for
Tree, just like there are (at least) two Applicative instances for
lists, one that "zips" the lists elementwise and one that takes all
possible combinations. You can do something similar with trees;
Maciej's instance corresponds to "zipping" two trees together, but you
can also do something like combining the functions in the first tree
in every possible way with the values in the second tree, the
complicated part is figuring out how to put all these results back
together into a tree.
But at any rate, you *don't* need an Applicative instance in order to
define a Traversable instance. Traversable instances follow a nice
regular pattern; they look exactly like Functor instances but with
normal application replaced by application in an Applicative context.
So, in your case:
instance Traversable Tree where
traverse f Empty = pure Empty
traverse f (Leaf x) = Leaf <$> f x
traverse f (Node l x r) = Node <$> traverse f l <*> f x <*> traverse f r
The thing to keep in mind is that the Applicative instance being used
here is NOT the one for Tree (which need not even have one), it is
whatever Applicative the caller of traverse is choosing to use as the
context of the traversal. All the traverse implementation has to do
is apply f to every value in the tree from left to right.
-Brent
------------------------------
Message: 6
Date: Wed, 24 Mar 2010 11:23:05 +0100
From: Heinrich Apfelmus <[email protected]>
Subject: [Haskell-beginners] Re: Memory usage problem
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=UTF-8
Sami Liedes wrote:
> Patrick LeBoutillier wrote:
>> I'm no profiling expert, but I have a few questions though:
>>
>> - What is the size (in bytes) of your input file?
>
> The input file contains 31,129,639 bytes, with 710,355 lines and 27,954
> individual packages/records.
>
> In fact it seems that even if the input stream repeats only the line
> " a" (that is, a space and the letter a) infinitely, the program
> eventually eats all memory. That's interesting.
>
> So I guess the lines are read in, but then held in memory and lazily
> not processed further until the entire file has been read, because
> it's not necessary? Or something.
Yep, pretty much. Basically, readRecords returns a list of unevaluated
expressions of type Package . But because they haven't been fully
evaluated yet, they still contain a lot of references to the input stream.
This wouldn't be a problem if the list itself were unevaluated, but it
appears that sort is forcing the spine of the list much earlier than
its elements, which means that you've read the whole file into memory
without also parsing each package into a Package record. This way, you
retain way too much of the input file.
A quick fix would be to intersperse a function between sort and
readRecords that imposes proper evaluation order:
import Control.Parallel.Strategies -- or Control.DeepSeq
instance NFData Package where
rnf (Package n v) = rnf n `seq` rnf v `seq` ()
processFile =
unlines . map sprintPackage
. sort . strictify . readRecords . lines
where
strictify [] = []
strictify (x:xs) = rnf x `seq` (x : strictify xs)
Here strictify makes sure that each cons cell comes with a fully
evaluated element x while the list itself is still lazy. (Since sort
has to evaluate the list anyway, the latter doesn't really matter and
you could as well use
strictify xs = rnf xs `seq` xs
)
While I expect the above to work, I hesitate to claim that it actually
does. The reason is that I don't understand your readRecords function
at a glance, unlike the processFile pipeline, it is not apparent how
it works. Since finding and fixing space leaks is easier if your code is
more obvious, I recommend to reformulate it as a function composition as
well, for instance something like this:
import Control.Arrow ((&&&))
import Data.Maybe (catMaybes)
import Daya.List (stripPrefix)
readRecords = map readRecord . splitByEmptyLines
splitByEmptyLines = filter (not . null) . groupBy (\x y -> y /= "")
readRecord =
uncurry Package
. (prefix "Name: " &&& prefix "Version: ")
. filter (not . beginsWithSpace)
where
beginsWithSpace (' ':xs) = True
beginsWithSpace _ = False
-- be warned, head may raise an exception
prefix s = head . catMaybes . map (stripPrefix s)
The rule is that explicit recursion should be replaced by high level
recursion schemes like map , filter , fold , concat etc. whenever
applicable.
This way, it's much easier to see how much of the input is retained for
each Package . For instance, your original readRecord function could
read an arbitrary number of lines, while here, it's clear that
readRecord can't cross the "boundary" imposed by splitByEmptyLines .
Regards,
Heinrich Apfelmus
--
http://apfelmus.nfshost.com
------------------------------
Message: 7
Date: Wed, 24 Mar 2010 15:14:28 +0100
From: Dupont Corentin <[email protected]>
Subject: [Haskell-beginners] web
To: [email protected]
Message-ID:
<[email protected]>
Content-Type: text/plain; charset=ISO-8859-1
Hello,
what would you use to grab data displayed on a web site (several pages
hyper-linked)?
And then to compute and display statistics over that data?
Thanks,
Corentin
------------------------------
Message: 8
Date: Wed, 24 Mar 2010 10:46:16 -0400
From: Alex Rozenshteyn <[email protected]>
Subject: Re: [Haskell-beginners] web
To: Dupont Corentin <[email protected]>
Cc: [email protected]
Message-ID:
<[email protected]>
Content-Type: text/plain; charset="utf-8"
TagSoup is probably what you want. Here's a good introduction to it:
http://community.haskell.org/~ndm/darcs/tagsoup/tagsoup.htm
On Wed, Mar 24, 2010 at 10:14 AM, Dupont Corentin <[email protected]
> wrote:
> Hello,
> what would you use to grab data displayed on a web site (several pages
> hyper-linked)?
> And then to compute and display statistics over that data?
>
> Thanks,
> Corentin
> _______________________________________________
> Beginners mailing list
> [email protected]
> http://www.haskell.org/mailman/listinfo/beginners
>
--
Alex R
-------------- next part --------------
An HTML attachment was scrubbed...
URL:
http://www.haskell.org/pipermail/beginners/attachments/20100324/4e4bcebe/attachment.html
------------------------------
_______________________________________________
Beginners mailing list
[email protected]
http://www.haskell.org/mailman/listinfo/beginners
End of Beginners Digest, Vol 21, Issue 25
*****************************************