[Haskell-beginners] Help with "20 intermediate haskell exercises"

Brent Yorgey byorgey at seas.upenn.edu
Mon Jul 6 17:10:22 EDT 2009


On Mon, Jul 06, 2009 at 03:55:34PM -0400, Patrick LeBoutillier wrote:
> Hi,
> 
> On Sun, Jul 5, 2009 at 3:44 PM, Daniel Fischer<daniel.is.fischer at web.de> wrote:
> > Am Sonntag 05 Juli 2009 21:05:20 schrieb Patrick LeBoutillier:
> >> Hi,
> >>
> >> Thanks for the help. I figured it out after that. I'm having a hard
> >> time with the other exercises though, I'm currently stuck at 14:
> >>
> >>
> >> class Misty m where
> >>   banana :: (a -> m b) -> m a -> m b
> >>   unicorn :: a -> m a
> >>
> >> -- Exercise 14
> >> -- Relative Difficulty: 6
> >> moppy :: (Misty m) => [a] -> (a -> m b) -> m [b]
> >> moppy = error "todo"
> >
> > moppy [] mop = ?
> > moppy (a:as) mop = (mop a) ?? (moppy as mop)
> >
> > use (among other things) banana and unicorn to replace the question marks
> 
> I came up with this:moppy [] mop = unicorn []
> moppy (a:as) mop = banana (\b -> banana (\bs -> unicorn (b:bs)) (moppy
> as mop)) (mop a)
> 
> 
> moppy [] mop = unicorn []
> moppy (a:as) mop = banana (\b -> banana (\bs -> unicorn (b:bs)) (moppy
> as mop)) (mop a)
> 
> How do I make the second one nicer/shorter?

Great!  You can't make it much shorter just using banana and unicorn.
But you could make it a little nicer like so:

  ananab = flip banana

  moppy (a:as) mop = mop a `ananab` (\b -> moppy as mop `ananab` (\bs -> unicorn (b:bs))

That makes it a bit more obvious where the 'b' and 'bs' are coming from.

You can also do something like this:

  liftBanana2 f mx my = mx `ananab` (\x -> my `ananab` (\y -> unicorn (f x y)))

  moppy (a:as) mop = liftBanana2 (:) (mop a) (moppy as mop)

I'll let you figure out what 'ananab' and 'liftBanana2' are called in the standard libraries. =)

-Brent


More information about the Beginners mailing list