Haskell: How do you figure out the definition of <*> from a Monad definition?

96 views Asked by At

I have a parser object defined:

newtype Parser a = Parser (String -> [(String, a)])

And a function to produce them:

produce :: a -> Parser a
produce x = Parser (\ts -> [(ts, x)])

And an instance of Monad for this parser object to allow me to bind multiple parsers into one:

instance Monad Parser where
  return = produce
  Parser px >>= f = Parser (\ts ->
   concat([parse (f x) ts' | (ts', x) <- px ts]))

I have also been using <*> quite happily to chain multiple parsers for different types to parse a string with different parts within it.

Of course <*> is defined via the following:

(<*>) = ap

But I want to define it explicitly so that I am able to understand and explain how it works exactly and I have been unable to figure it out.

So how can I figure out how to explicitlly find the definition of ap or <*> in this instance?

Any advice on what <*> would be or how I should work it out is appreciated.

Thanks.

1

There are 1 answers

0
chi On BEST ANSWER

You can start from

f <*> x = do
    f' <- f
    x' <- x
    return (f' x')

or, equivalently

f <*> x =
    f     >>= (\f' ->
    x     >>= (\x' ->
    return (f' x')))

and then expand >>= and return as needed.