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:  Points-free style (Jonas Almstr?m Dureg?rd)
   2. Re:  I don't understand mapM in mapM id (Just 1, Nothing,
      Just 3) (Sebastian Hungerecker)
   3.  What's wrong with my code? (Zhi-Qiang Lei)
   4. Re:  Confused by type constraints (Guy)
   5.  Seeking some clarification... (Sean Charles)


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

Message: 1
Date: Sun, 5 Jun 2011 18:09:38 +0200
From: Jonas Almstr?m Dureg?rd <[email protected]>
Subject: Re: [Haskell-beginners] Points-free style
To: Daniel Fischer <[email protected]>
Cc: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset="iso-8859-1"

Or you could use curry and uncurry:

sumProducts = curry $ sum . uncurry (zipWith (*))

On 5 June 2011 17:40, Daniel Fischer <[email protected]>wrote:

> On Sonntag, 5. Juni 2011, 17:09, Alexander Shendi wrote:
> > Hi folks,
> >
> > I am working my way through "Learn You a Haskell for Great Good" and
> > have reached page 84, where the book recommends that you define your
> > functions in a "points-free style", using the "." and "$" operators.
> >
> > Now I have:
> >
> > sumProducts' :: Num a => [a] -> [a] -> a
> > sumProducts' x y = sum (zipWith (*) x y)
> >
> > I would like to eliminate the "x" and the "y" in the definition, but all
> > I have managed to contrive is:
> >
> > sumProducts :: Num a => [a] -> [a] -> a
> > sumProducts x = sum . zipWith (*) x
> >
> > How do I proceed from here? Any advice is welcome :)
> >
> > Many thanks in advance,
> >
> > /Alexander
>
> First, (mentally) insert parentheses:
>
> sumProducts x = sum . (zipWith (*) x)
>
> Now, write the composition as a prefix application of (.),
>
> sumProducts x = (.) sum (zipWith (*) x)
> = ((.) sum) (zipWith (*) x)
>
> which has the form f (g x), with f = (.) sum and g = zipWith (*), so it's
>
> (f . g) x, which expands to
>
> (((.) sum) . (zipWith (*))) x
>
> and now the argument can easily be dropped, giving
>
> sumProducts = ((.) sum) . (zipWith (*))
>
> now to make it look a little nicer, we can remove unnecessary parentheses
> and write (.) sum as a section,
>
> sumProducts = (sum .) . zipWith (*)
>
> Generally, pointfreeing goes
>
> f (g x) ~> f . g
> f (g x y) ~> (f .) . g
> f (g x y z) ~> ((f .) .) . g
>
> Play with it and get a little experience, but don't overuse it.
> Nobody really wants to come across a pointfree version of
>
> \a b c d e f g h -> foo (bar a b) (baz c d e) f (quux g h)
>
> (and that's not even repeating or flipping arguments)
>
> _______________________________________________
> Beginners mailing list
> [email protected]
> http://www.haskell.org/mailman/listinfo/beginners
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 
<http://www.haskell.org/pipermail/beginners/attachments/20110605/0d8d6975/attachment-0001.htm>

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

Message: 2
Date: Sun, 05 Jun 2011 18:31:37 +0200
From: Sebastian Hungerecker <[email protected]>
Subject: Re: [Haskell-beginners] I don't understand mapM in mapM id
        (Just 1, Nothing, Just 3)
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

On 05.06.2011 14:40, Haisheng Wu wrote:
> By looking at sequence implementation in Hugs:
>
> sequence (c:cs) = do x<- c
>       xs<- sequence cs
>       return (x:xs)
>
> Apply it against a list [Just 2, Nothing], we will have:
>    sequence [Just 2, Nothing]
> = do x<- Just 2
>       y<- sequence [Nothing]
>    return (x:y)
> = return (2:Nothing)
>
> The question is
> Why/How `return (2:Nothing)` eval to `Nothing` ?
>    

It doesn't. You went wrong in the last equality there. y doesn't have
the value Nothing, in fact it never gets a value at all.
Let's first look at what sequence [Nothing] evaluates to:

do x <- Nothing
    y <- sequence [Nothing]
    return (x:y)

Since  Nothing >>= f  evaluates to Nothing this means that the above
do-block evaluates to Nothing, too. So  y <- sequence [Nothing]  becomes
y <- Nothing  and again the whole expression evaluates to Nothing and
return (x:y)  never is evaluated.



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

Message: 3
Date: Mon, 6 Jun 2011 00:32:20 +0800
From: Zhi-Qiang Lei <[email protected]>
Subject: [Haskell-beginners] What's wrong with my code?
To: Haskell Beginer <[email protected]>
Message-ID: <[email protected]>
Content-Type: text/plain; charset="utf-8"

Dear All,

I almost finish the chapter 3 of Real World Haskell. The last exercise blocks 
me. My code will crash while running. Does anyone can tell me which part is 
wrong in my code? Thanks.

Question:
Using the code from the preceding three exercises, implement Graham's scan 
algorithm for the convex hull of a set of 2D points. You can find good 
description of what a convex hull. is, and how the Graham scan algorithm should 
work, on Wikipedia.

Answer:

-- Graham Scan, get the convex hull.
-- Implement the algorithm on http://en.wikipedia.org/wiki/Graham_scan

import Data.List
import Data.Ord

data Direction = TurnLeft | TurnRight | GoStraight deriving (Eq, Show)

-- Determine if three points constitute a "left turn" or "right turn" or "go 
straight".
-- For three points (x1,y1), (x2,y2) and (x3,y3), simply compute the direction 
of the cross product of the two vectors defined by points (x1,y1), (x2,y2) and 
(x1,y1), (x3,y3), characterized by the sign of the expression (x2 ? x1)(y3 ? 
y1) ? (y2 ? y1)(x3 ? x1). If the result is 0, the points are collinear; if it 
is positive, the three points constitute a "left turn", otherwise a "right 
turn".
direction a b c = case compare ((x2 - x1) * (y3 - y1)) ((y2 - y1) * (x3 - x1)) 
of
    EQ -> GoStraight
    GT -> TurnLeft
    LT -> TurnRight
    where   x1 = fst a
            y1 = snd a
            x2 = fst b
            y2 = snd b
            x3 = fst c
            y3 = snd c

grahamScan points = scan (sort points)
            -- For each point, it is determined whether moving from the two 
previously considered points to this point is a "left turn" or a "right turn". 
If it is a "right turn", this means that the second-to-last point is not part 
of the convex hull and should be removed from consideration. This process is 
continued for as long as the set of the last three points is a "right turn". As 
soon as a "left turn" is encountered, the algorithm moves on to the next point 
in the sorted array. (If at any stage the three points are collinear, one may 
opt either to discard or to report it, since in some applications it is 
required to find all points on the boundary of the convex hull.)
    where   scan (a : (b : (c : points)))
                | (direction a b c) == TurnRight    = scan (a : (c : points))
                | otherwise                         = a : (scan (b : (c : 
points)))
            scan (a : (b : []))                     = []
            -- Put prime to the head.
            sort points                             = prime : (reverse (sortBy 
(compareByCosine prime) rest))
                        -- Sort a list to compute. The first step is to find a 
point whose y-coordinate is lowest. If there are more than one points with 
lowest y-coordinate, take the one whose x-coordinate is lowest. I name it prime.
                where   compareByYAndX a b
                            | compareByY == EQ  = comparing fst a b
                            | otherwise         = compareByY
                            where   compareByY  = comparing snd a b 
                        prime                   = minimumBy compareByYAndX 
points
                        -- Delete prime from the candidate points. Sort the 
rest part by the cosine value of the angle between each vector from prime to 
each point. Reverse it and put prime to the head.
                        rest                    = delete prime points
                        compareByCosine p a b   = comparing cosine pa pb
                            where   pa          = (fst a - fst p, snd a - snd p)
                                    pb          = (fst b - fst p, snd b - snd p)
                                    cosine v    = x / sqrt (x ^ 2 + y ^ 2)
                                        where   x = fst v
                                                y = snd v


Best regards,
Zhi-Qiang Lei
[email protected]

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 
<http://www.haskell.org/pipermail/beginners/attachments/20110606/437e5c5e/attachment-0001.htm>

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

Message: 4
Date: Sun, 05 Jun 2011 19:53:50 +0300
From: Guy <[email protected]>
Subject: Re: [Haskell-beginners] Confused by type constraints
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

On 04/06/2011 22:49, Brent Yorgey wrote:
> On Fri, Jun 03, 2011 at 05:13:43PM +0300, Guy wrote:
>> On 03/06/2011 16:55, Daniel Schoepe wrote:
>>> On Fri, 03 Jun 2011 16:04:05 +0300, Guy<[email protected]>   wrote:
>>>> I have some code resembling
>>>>
>>>> class Foo f where
>>>>    foo :: a ->   f a
>>>>
>>>> data Bar f a = Foo f =>   Bar {bar :: f a}
>>>>
>>>> instance Foo (Bar f) where
>>>>    foo a = Bar $ foo a
>>>>
>>>> GHC insists on Foo f =>   in the instance declaration. However, the 
>>>> definition of Bar guarantees that this will always be
>>>> the case. Why do I have to state this explicitly?
>>>
>>> The constraints in the data type declaration only affect the
>>> constructors. It's a known issue, unfortunately there doesn't seem to be
>>> a way around it.
>>
>> It seems to work for simpler examples. For example, this is OK
>>
>> data X x = Show x =>  X x
>>
>> s :: X x ->  String
>> s (X x) = show x
>>
>> I don't have to add a Show x =>  type constraint to s.
>
> In this case, you are *destructing* an X value, and when you do, the
> Show constraint on x becomes available, since the X constructor is
> always paired with a Show constraint.
>
> In your original example, you are *constructing* a Bar value.  You
> have stated that the Bar constructor must be accompanied by a Foo
> constraint, but there is no such constraint in sight!
>
> So the difference is between *destructing* a value (when the
> associated constraint becomes available) and *constructing* one (when
> the required constraint must be provided).
>
> I don't know if I've explained that well.  As others have mentioned,
> the ability to specify constraints on constructors in this way is
> probably going to be removed from the language anyway.

So in my original example, why isn't "instance Foo (Bar f)" destructing Bar - 
and making the constraint available?




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

Message: 5
Date: Sun, 05 Jun 2011 19:46:41 +0100
From: Sean Charles <[email protected]>
Subject: [Haskell-beginners] Seeking some clarification...
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset="iso-8859-1"; Format="flowed"

I have a CSV file containing some data about trains: stations from, to,
times etc. and I wanted to 'learn some more Haskell' and, to my 
astonishment,
I have gotten thus far but I am not sure *why* it works or *how* I got
there! LMAO Here is the relevant code ...

====>
trains :: String -> IO ()
trains csvfile = do
      legodata <- parseCSVFromFile csvfile
      case legodata of
          Left error -> print error
          Right legodata -> mapM_ putStrLn (trainCodes legodata)

-- Assumes row 1 contains cell header information
-- Note: the train-code is always the third cell

trainCodes :: [Record] -> [String]
trainCodes = nub . map (!! 2) . tail
====>

I was chuffed with writing the trainCodes as a point-free function,
that sort of thing is getting a little easier to work with but I still
have real head-banging frustrations sometimes with seemingly simple
things, like looping and just printing stuff out, despite having taught 
myself
LISP six years ago and Erlang in recent years! I quit!! I really do!!!

My confusion arises over: mapM_ putStrLn (traincodes legodata)
Given that: mapM_ :: Monad 
<http://haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/Control-Monad.html#t%3AMonad>
 
m => (a -> m b) -> [a] -> m () 
<http://haskell.org/ghc/docs/6.12.2/html/libraries/ghc-prim-0.2.0.0/GHC-Unit.html#t%3A%28%29>

Here's how I read it: For any m that is a Monad, mapM_ takes a function 
that "takes
an 'a' and returns it wrapped in a monad", a "list of a's" and returns a 
"monad containing
'unit'", the empty-list LISP-() undefined voidy thing.

Given that: putStrLn :: String 
<http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#t:String>
 
-> IO 
<http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#t:IO>
 
() 
<http://hackage.haskell.org/packages/archive/base/latest/doc/ghc-prim-0.2.0.0/GHC-Unit.html#t:-40--41->,
 
this means that 'a' is String and 'm b' is
IO () and my list of [a] is the result of calling 'traincodes legodata'.

trainCodes = nub . map (!! 2) . tail

legodata is [Record] (from Text.CSV) and so, 'tail' removes the header 
row from
the data, 'map (!! 2)' extracts the third  field from each row and 
finally 'nub'
removes the duplicates. Thus the return type from trainCodes is [String].

Gluing it all together:

mapM_ :: Monad 
<http://haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/Control-Monad.html#t%3AMonad>
 
m => (a -> m b) -> [a] -> m () 
<http://haskell.org/ghc/docs/6.12.2/html/libraries/ghc-prim-0.2.0.0/GHC-Unit.html#t%3A%28%29>
putStrLn :: String 
<http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#t:String>
 
-> IO 
<http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#t:IO>
 
() 
<http://hackage.haskell.org/packages/archive/base/latest/doc/ghc-prim-0.2.0.0/GHC-Unit.html#t:-40--41->
trainCodes :: [Record] -> [String]

the type of my call then would seem to be:

String -> IO () -> [String] -> IO ()
"putStrLn" -> (trainCodes legodata) -> IO ()

which means that not only have I got the types correct for the call but 
the result
type of 'IO ()' also satisfies the type return for my function and hence 
it executes
from 'main' (where it is called from) with no issues.

So, am I finally beginning to get a grip on it all ? This list is a 
constant source
of education and I don't post very often as you guys give me far too 
much stuff to
be reading all the time! :)

I am using Text.CSV to read my file and all I wanted to do was to output
a list of unique codes from column three of the spreadsheet data, one per
line, so that I can use this Haskell as part of a bigger 'bash' script.

Any detailed explanations that might help me better understand my solution
would be welcome; right now I feel I 'just got lucky' although there must
be a glimmer of understanding somewhere! LOL

Thanks,
Sean.

PS: Phew!

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 
<http://www.haskell.org/pipermail/beginners/attachments/20110605/e3670f4e/attachment.htm>

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

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


End of Beginners Digest, Vol 36, Issue 12
*****************************************

Reply via email to