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:  Trivial function of type (a -> b) -> Maybe a         -> Maybe b
      (Yusaku Hashimoto)
   2. Re:  Code help requested (Tim Perry)
   3. Re:  Code help requested (Daniel Fischer)
   4.  Design Question (Jonathan Fischoff)
   5.  Re: Understanding Monadic I/O (Heinrich Apfelmus)
   6. Re:  Re: Understanding Monadic I/O (Markus B?hm)
   7. Re:  Understanding Monadic I/O (David Virebayre)


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

Message: 1
Date: Thu, 14 Jan 2010 02:18:54 +0900
From: Yusaku Hashimoto <[email protected]>
Subject: Re: [Haskell-beginners] Trivial function of type (a -> b) ->
        Maybe a         -> Maybe b
To: Eugen Zagorodniy <[email protected]>
Cc: [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset=UTF-8

> Sure that is it. I should pay more attention to standard type classes.

Typeclassopedia will help you to understand these type classes:
http://www.haskell.org/sitewiki/images/8/85/TMR-Issue13.pdf

-- nwn

On Thu, Jan 14, 2010 at 12:01 AM, Eugen Zagorodniy
<[email protected]> wrote:
> Wed, 13 Jan 2010 08:47:42 -0600 Antoine Latter:
>> On Wed, Jan 13, 2010 at 8:44 AM, Eugen Zagorodniy
>> <[email protected]> wrote:
>> > Greetings!
>> >
>> > I looked at documentation of Maybe type and suprisingly found no
>> > function like
>> >
>> > maybize             :: (a -> b) -> Maybe a -> Maybe b
>> > maybize f Nothing   =  Nothing
>> > maybize f (Just x)  =  Just (f x)
>> >
>>
>> Have you looked at:
>>
>> fmap :: Functor f => (a -> b) -> f a -> f b
>>
>> It will do what you want, and has the bonus of doing the same
>> operation for a lot more structures.
>
> Sure that is it. I should pay more attention to standard type classes.
>
> Thanks!
> _______________________________________________
> Beginners mailing list
> [email protected]
> http://www.haskell.org/mailman/listinfo/beginners
>


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

Message: 2
Date: Wed, 13 Jan 2010 11:58:17 -0800 (PST)
From: Tim Perry <[email protected]>
Subject: Re: [Haskell-beginners] Code help requested
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=us-ascii

A side benefit of using foldl' instead of foldr is that I can now run it 
against the entire dictionary!

I found a good explanation of why here:
http://www.haskell.org/haskellwiki/Foldr_Foldl_Foldl%27




----- Original Message ----
From: Daniel Fischer <[email protected]>
To: [email protected]
Cc: Tim Perry <[email protected]>
Sent: Wed, January 13, 2010 2:56:45 AM
Subject: Re: [Haskell-beginners] Code help requested

Am Mittwoch 13 Januar 2010 03:38:46 schrieb Tim Perry:
> I compiled the original version, Yusaka's version, and a version I wrote
> and found the following:
>
> $ time ./Anagram_me < /usr/share/dict/words > /dev/null
> real    0m2.197s
> user    0m2.040s
> sys     0m0.160s
>
> $ time ./Anagram_JoeVanDyke < /usr/share/dict/words > /dev/null
> real    0m4.570s
> user    0m4.290s
> sys     0m0.260s
>
> pe...@emperor:~/haskell$ time ./Anagram_Yusaku < /usr/share/dict/words >
> /dev/null real    0m1.337s
> user    0m1.230s
> sys     0m0.100s
>
>
> From
> this, it looks like mine version takes less than half the time of the
> original. However, if I run a bigger dictionary (Ubuntu package
> wamerican-large instead of wamerican-small) then I'm only about 30%
> faster than the original. This makes me think I have some sort of
> exponential data structure growth going on.  Here is my version. Can
> anyone confirm that data structure growth is the problem with my
> approach?  Thanks, Tim
>
>
>
> import Data.List as Lst
> import Data.Map as Map
>
> -- This version only displays words that have more than two
> -- match in the list, and sorts by the words that got the most matches.
>
> -- Can we do the map bit better?
>
> main = do
>   input <- getContents
>   print $ anagrams $ lines input
>
> anagrams words =
>   sorted_anagrams
>   where
>     sorted_anagrams = sortBy sorter filtered_anagrams
>     sorter a b = compare (length b) (length a)
>     longEnoughWords = [x | x <- words, length x > 1]

The words are short here, so it's not catastrophic, but

*don't use length unless you really want to know the length*

Here, use (not . null . drop 1) [an input line might be empty, so don't use 
tail], in general, instead of 

length list > k, use not . null $ drop k list;

if you want to check (length list == k),

case drop (k-1) list of
  (_:[]) -> True
_      -> False

is O(min k (length list)), if there's a slight possibility that the list is 
much longer than k, it's safer.

However, it's unlikely that there are more than 52 one-letter words in the 
word list, so filtering out those shouldn't make it faster.

>     filtered_anagrams = [x | x <- Map.elems $ foldr insert empty $
> wordPairs, length x > 2] where

That's bad. 

Using foldr to construct the map, you must have the whole list from which 
to construct it in the memory at once - since the list takes less memory 
than the map, that is not a real problem, if you run out of memory thus, 
you would anyway - and can start constructing the map only after the entire 
reading is done - this is the real problem. 
You build a nice huge thunk that way, which may blow the stack. And it's 
slow.

foldr is for the cases where you can start returning output before the 
entire list has been consumed, a necessary condition for that is that the 
accumulation function is lazy in its second argument, like (++), (&&), 
(||).
In practically all other cases, you want foldl' (there might be a few cases 
where foldl is what you want, I haven't seen such a case yet, though).

>          wordPairs =  zip (Prelude.map Lst.sort longEnoughWords)
>                                    longEnoughWords
>          insert (sorted, original) = insertWith (++) sorted [original]

changing foldr to foldl' and insert to

insert m (sorted,original) = insertWith (++) sorted [original] m

reduces the time on my /usr/share/dict/words from 31 seconds to 8.

The difference is 0.64s vs 0.76s for 40,000 words, 1.17s vs. 1.80s on 
70,000 words, 2.12s vs. 4.22s on 120,000 words.


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

Message: 3
Date: Wed, 13 Jan 2010 23:11:02 +0100
From: Daniel Fischer <[email protected]>
Subject: Re: [Haskell-beginners] Code help requested
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain;  charset="iso-8859-1"

Am Mittwoch 13 Januar 2010 20:58:17 schrieb Tim Perry:
> A side benefit of using foldl' instead of foldr is that I can now run it
> against the entire dictionary!
>
> I found a good explanation of why here:
> http://www.haskell.org/haskellwiki/Foldr_Foldl_Foldl%27
>

Yep. One thing, though: seq, and hence foldl' only evaluates to weak head 
normal form (WHNF), that is (leaving aside lambda expressions), to the 
topmost constructor.
So, e.g. list `seq` value only checks whether list is [] or (_:_), that may 
not be enough strictness in a fold. The constructors of Map are strict 
enough to avoid large thunks in general with foldl', but for example to 
compute the average of a list of numbers:

average :: [Double] -> Double
average list = sumList / countList
   where
      (sumList,countList) = foldl' add (0,0) list
      add (s,c) x = (s+x,c+1)

isn't strict enough, sumList and countList will be large thunks because in 
each step add (s,c) x will be evaluated enough only to see that it is 
indeed a pair.

For such cases, one needs to force the evaluation further by hand.
One possibility is to write a stricter function:

add' (s,c) x
   = let s1 = s+x
         c1 = c+1
     in s1 `seq` c1 `seq` (s1,c1)

or, using BangPatterns:

add' (!s,!c) x = (s+x,c+1)

Another possibility is to use a sufficiently strict data type

data DPair = DP !Double !Double

add (DP s c) x = DP (s+x) (c+1)

(the strict fields will keep the numbers completely evaluated at each 
step), a third is to use rnf {- reduce to normal form -} from 
Control.Parallel.Strategies or another sufficiently strict strategy, 
respectively deepseq.

Which one is the best choice varies of course.


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

Message: 4
Date: Wed, 13 Jan 2010 17:54:51 -0800
From: Jonathan Fischoff <[email protected]>
Subject: [Haskell-beginners] Design Question
To: [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset="iso-8859-1"

I am writing graphics code, and there is a pattern that I am repeating. I
imagine that there could be some way to automate the code that I am
creating.

I have a collection of type classes like the ones below (minus fundeps, and
other elements to make it compile).

class Vertex a ...

class (Coordinate b, Vertex a) => Positionable a b where
     getPosition :: a -> b

class (Vertex a) => Colorable a where
     getColor :: a -> Color

class (Vertex a) => Textureable a where
     getUVs :: a -> (Double, Double)

etc... Basically I have a bunch of type classes with one method getSomeType.

The following would be an instance of all of the type classes:
data ColorVertex = ColorVertex Cart3Coordinate Color (Double, Double)

Additionally I have collection type classes as follows:

class (Coordinate b) => PositionCollection a b where
     getPositionList :: a -> [b]

class ColorList a where
     getColorList :: a -> [Color]

class UVList a where
     getUVList :: a -> [(Double, Double)]

So, for every getSomeType class, there is a getSomeTypeList class. An
instance of these types would look like

data StreamCollection3 = StreamCollection3 [Cart3Coordinate] [Color]
[(Double, Double)]

add it would also an instance of the following class, and I would like to
figure out how to generate the functions for the class.

class (Vertex b) => VertexCollection  a b where
    getElement :: a -> Int -> b
    getVertexList :: a -> [b]
    fromVertexList :: [b] -> a

The Vertex in this case would be ColorVertex.

I was thinking I could reduce the code by making the classes

class Gets a b where
     gets :: a -> b

class GetsList a b where
     getsList :: a -> [b]

But I think I could go further. I'm wondering if there is a way to
completely automate the construction of these classes, data types and
methods, such that all I would provide is definition of the element type
such as

data PositionVertex = PositionVertex Cart3Coordinate

and everything else would get generated.

I can see how I would write code to generate this. Is the time to learn
Template Haskell, or is there another way to generate my boilerplate?

-Jonathan Fischoff
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 
http://www.haskell.org/pipermail/beginners/attachments/20100113/ade6c41f/attachment-0001.html

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

Message: 5
Date: Thu, 14 Jan 2010 10:36:14 +0100
From: Heinrich Apfelmus <[email protected]>
Subject: [Haskell-beginners] Re: Understanding Monadic I/O
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=UTF-8

Markus Böhm wrote:
> Hi, I'd like to understand in principle, how monadic I/O actions and
> combinators (>>=) are translated into imperative C--, to be executed
> sequentially.
> 
> Does sequencing of IO actions mean nesting of C-- functions and
> passing values/state via additional function parameters?
>
> Is there any material with examples available?
> 
> P.S.: Just to understand the magic better. I need it.

Well, the key point of the IO monad is of course that the internals are
abstracted away. I'm not sure you will get much understanding out of them.


If I am informed correctly, GHC represents IO as

   newtype IO a = IO ( World -> (# a, World #) )

But  World  is just a dummy type, it models the execution order as data
dependencies so that the optimizer doesn't mess with it. In other word,
 World  is stripped out completely, primitives like  putChar  are pretty
much just compiled down to foreign function calls in C--.

There are other possibilities, I believe NHC and YHC represent IO as

   newtype IO a = IO ( World -> a )

Again, the  World  argument is just a dummy.


Regards,
Heinrich Apfelmus

--
http://apfelmus.nfshost.com



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

Message: 6
Date: Thu, 14 Jan 2010 12:43:47 +0100
From: Markus B?hm <[email protected]>
Subject: Re: [Haskell-beginners] Re: Understanding Monadic I/O
To: Heinrich Apfelmus <[email protected]>
Cc: [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1

Tx Heinrich. Could You explain how this "modelling the execution order
as data dependency" works and how its tranlsated into sequential,
imperative code? I mean in principle/for dummies.

>From my beginner's perspective I feel I need that insight to
understand how sustainable the abstraction is.

P.S.: Looking at forum discussions about simple, standard examples
like Fibonacci, arithmetic mean etc. I get the impression that the
naive, beautiful solution is evtl. not scalable (performance, memory)
and that it's necessary to understand the runtime behaviour underneath
the abstraction. Would You confirm that impression?

-- Markus




On Thu, Jan 14, 2010 at 10:36 AM, Heinrich Apfelmus
<[email protected]> wrote:
> Markus Böhm wrote:
>> Hi, I'd like to understand in principle, how monadic I/O actions and
>> combinators (>>=) are translated into imperative C--, to be executed
>> sequentially.
>>
>> Does sequencing of IO actions mean nesting of C-- functions and
>> passing values/state via additional function parameters?
>>
>> Is there any material with examples available?
>>
>> P.S.: Just to understand the magic better. I need it.
>
> Well, the key point of the IO monad is of course that the internals are
> abstracted away. I'm not sure you will get much understanding out of them.
>
>
> If I am informed correctly, GHC represents IO as
>
>   newtype IO a = IO ( World -> (# a, World #) )
>
> But  World  is just a dummy type, it models the execution order as data
> dependencies so that the optimizer doesn't mess with it. In other word,
>  World  is stripped out completely, primitives like  putChar  are pretty
> much just compiled down to foreign function calls in C--.
>
> There are other possibilities, I believe NHC and YHC represent IO as
>
>   newtype IO a = IO ( World -> a )
>
> Again, the  World  argument is just a dummy.
>
>
> Regards,
> Heinrich Apfelmus
>
> --
> http://apfelmus.nfshost.com
>
> _______________________________________________
> Beginners mailing list
> [email protected]
> http://www.haskell.org/mailman/listinfo/beginners
>


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

Message: 7
Date: Thu, 14 Jan 2010 13:52:01 +0100
From: David Virebayre <[email protected]>
Subject: Re: [Haskell-beginners] Understanding Monadic I/O
To: Markus B?hm <[email protected]>
Cc: [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset=UTF-8

On Mon, Jan 11, 2010 at 2:57 PM, Markus Böhm
<[email protected]> wrote:
> Hi, I'd like to understand in principle, how monadic I/O actions and
> combinators (>>=) are translated into imperative C--, to be executed
> sequentially.
>
> Does sequencing of IO actions mean nesting of C-- functions and
> passing values/state via additional function parameters?
>
> Is there any material with examples available?

Perhaps you could download JHC and compile with the -d c  flag.
It writes the C code, and JHC writes more understandable C code
compared to GHC (IMHO)

for example,

main = putStrLn "hello, world" >> putStrLn "hello again, world"

compiles to

[lots of stuff]

static void A_STD
ftheMain(void)
{
        jhc_function_inc();
        fPrelude__IO__putStr(PROMOTE(c12));
        (void)jhc_utf8_putchar((int)10);
        fPrelude__IO__putStr(PROMOTE(c23));
        return (void)jhc_utf8_putchar((int)10);
}

so in this simple example you see there's no nesting of functions.

David


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

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


End of Beginners Digest, Vol 19, Issue 10
*****************************************

Reply via email to