0

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.

James
  • 104
  • 1
  • 8
  • 2
    You can find the source for `ap` here: http://hackage.haskell.org/package/base-4.9.0.0/docs/src/GHC.Base.html#ap (although fun excercise to work it out yourself). substitute occurences of `return` and `>>=` with their right-hand sides from the implementations you posted above (just like in algebra class) – jberryman Dec 18 '16 at 04:54

1 Answers1

2

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.

Benjamin Hodgson
  • 42,952
  • 15
  • 108
  • 157
chi
  • 111,837
  • 3
  • 133
  • 218