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?
myGroupBy :: (a -> a -> Bool) -> [a] -> [[a]]
myGroupBy p xs =
foldr step [] xs
-- 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
On 2009 Mar 28, at 0:59, Jeff Lasslett wrote:
> myGroupBy :: (a -> a -> Bool) -> [a] -> [[a]]
> myGroupBy p xs =
> foldr step [] xs
> -- 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