[Haskell-beginners] Trying to find an alternative StateMonad

Daniel Fischer daniel.is.fischer at web.de
Wed Apr 14 19:15:51 EDT 2010


Am Donnerstag 15 April 2010 00:49:26 schrieb Patrick LeBoutillier:
> Hi,
>
> Sorry I can't be of much help here, but I have a question though:
> > data StateCmd a where
> >        Put :: a -> StateCmd a
> >        Undo :: StateCmd a
> >        Redo :: StateCmd a
> >                deriving (Show, Functor)
>
> I'm not familiar with the above syntax (data ... where).

It's GADT syntax, read about it in the user's guide.

> What does it do exactly?

That is exactly equivalent to

data StateCmd a
    = Put a
    | Undo
    | Redo
      deriving (...)

The coolness of GADTs is that you can have different constructors in your 
datatype for different type parameters:

data Expr p where
    Plain :: a -> Expr a
    Add :: Num a => Expr a -> Expr a -> Expr a
    If :: Expr Bool -> Expr a -> Expr a -> Expr a
    And :: Expr Bool -> Expr Bool -> Expr Bool
    ...

And you can pattern match on these constructors for different types in one 
function:

eval :: Expr a -> a
eval (Plain x) = x
eval (Add e1 e2) = eval e1 + eval e2
eval (If eb t f) = if eval eb then eval t else eval f
eval (And e1 e2) = eval e1 && eval e2
...

>
> Patrick



More information about the Beginners mailing list