[Haskell-cafe] Help with Programming in Haskell example
Tillmann Rendel
rendel at rbg.informatik.tu-darmstadt.de
Fri May 18 16:32:04 EDT 2007
Hello,
Andre Nathan schrieb:
> so I'm wondering what else I need to do for the "do"
> notation to work.
> import Prelude hiding ((>>=), return)
You explicitly ask for the well-known and standard functions >>= and
return to be hidden away, because you want to define your own versions.
> p :: Parser (Char, Char)
> p = do x <- item
> item
> y <- item
> return (x, y)
The do-notation is desugared to some calls of the well-known and
standard functions >>= and return, defined in the Prelude. Wich are
different from your own functions >>= and return. So you have to connect
your definitions of >>= and return to the well-known functions used by
the do notation.
To do so, you have to declare your Parser type an instance of the
somewhat magic do-notation-enableing typeclass Monad. Fortunately, this
is not too hard, because you can reuse your functions >>= and return.
First, change your Parser type to be a proper data type instead of a
type synonym (and change your code to correctly pack / unpack Parser
values):
> data Parser a = Parser (String -> [(a, String)])
Second, move >>= and return inside an instance declaration:
> instance Monad Parser where
> (Parser p) >>= f = ...
> return v = Parser (\inp -> [(v, inp)])
Third, stop hiding Prelude's >>= and return.
> import Prelude
Now you should be able to use do notation with your own Parser type.
Tillmann
More information about the Haskell-Cafe
mailing list