Why doesn't ghci load this?

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Why doesn't ghci load this?

Jeff Lasslett-2
Hi,

I've been making my way through the exercises in the book "Real World
Haskell".  Below is my solution to an exercise asking for an
implementation of groupBy in term sof a foldr.  I haven't tested it
extensively but is seems to work.

GHCI rejects it though, if I uncomment the type signature for the 'step'
function.  Could someone please help me to understand why that is?

Thanks,
Jeff

myGroupBy :: (a -> a -> Bool) -> [a] -> [[a]]
myGroupBy p xs =
 foldr step [[]] xs
 where
  -- step :: a -> [ [ a ] ] -> [ [ a ] ]
  step x acc@( ys : yss )
   | null ys                      = [ x ] : []
   | p x ( head ys )              = ( x : ys ) : yss
   | ( p x ( head ys ) ) == False = [ x ] : acc



Reply | Threaded
Open this post in threaded view
|

Why doesn't ghci load this?

Brandon S Allbery KF8NH
On 2009 Mar 28, at 0:59, Jeff Lasslett wrote:
> myGroupBy :: (a -> a -> Bool) -> [a] -> [[a]]
> myGroupBy p xs =
> foldr step [[]] xs
> where
>  -- step :: a -> [ [ a ] ] -> [ [ a ] ]
>  step x acc@( ys : yss )
>   | null ys                      = [ x ] : []
>   | p x ( head ys )              = ( x : ys ) : yss
>   | ( p x ( head ys ) ) == False = [ x ] : acc

In Haskell98, the type "a" in step is not the same as the one in  
myGroupBy.  If you use the ScopedTypeVariables extension (see the ghc  
manual; just adding the option won't work) you can write the type.

--
brandon s. allbery [solaris,freebsd,perl,pugs,haskell] [hidden email]
system administrator [openafs,heimdal,too many hats] [hidden email]
electrical and computer engineering, carnegie mellon university    KF8NH


-------------- next part --------------
A non-text attachment was scrubbed...
Name: PGP.sig
Type: application/pgp-signature
Size: 195 bytes
Desc: This is a digitally signed message part
Url : http://www.haskell.org/pipermail/beginners/attachments/20090328/9849f6ad/PGP.bin
Reply | Threaded
Open this post in threaded view
|

Re: Why doesn't ghci load this?

7stud-2
Brandon S. Allbery KF8NH <allbery <at> ece.cmu.edu> writes:

>
> On 2009 Mar 28, at 0:59, Jeff Lasslett wrote:
> > myGroupBy :: (a -> a -> Bool) -> [a] -> [[a]]
> > myGroupBy p xs =
> > foldr step [[]] xs
> > where
> >  -- step :: a -> [ [ a ] ] -> [ [ a ] ]
> >  step x acc@( ys : yss )
> >   | null ys                      = [ x ] : []

I wonder whether that line does anything?  foldr is defined like
this:

foldr step zero (x:xs) = step x (foldr step zero xs)

So it seems to me that when the step function doesn't affect
either the accumulator(=zero) or xs, then the step function
won't have any effect on the result foldr produces.

The return value from your 'null ys' guard does not affect
xs, nor does it change the accumulator acc.  So how does
it affect the result of foldr?