[Haskell-cafe] foild function for expressions

Kalman Noel kalman.noel at bluebottle.com
Mon Dec 3 12:43:00 EST 2007


Carlo Vivari wrote:
> data AlgExp a = AlgExp
> { litI  :: Int -> a,
>    litB :: Bool -> a,
>    add :: a -> a -> a,
>    and :: a -> a -> a,
>    ifte :: a -> a -> a -> a}

You're confusing sum and product types. That is, you're using a product type,
but you probably need a sum type, like this:

    data Exp1 = LitI Int 
                | LitB Bool 
                | Add Exp1 Exp1 
                | And Exp1 Exp1 
                | IfThenElse Exp1 Exp1 Exp1

But in this case, using GADTs (beware: not Haskell 98, but a very popular
extension) makes for a more elegant solution. Note the strong types, disallowing
e. g. the addition of a number to a boolean value:

    data Exp2 a where
        LitI        :: Int  -> Exp2 Int
        LitB        :: Bool -> Exp2 Bool
        Add         :: Exp2 Int  -> Exp2 Int  -> Exp2 Int
        And         :: Exp2 Bool -> Exp2 Bool -> Exp2 Bool
        IfThenElse  :: Exp2 Bool -> Exp2 a -> Exp2 a -> Exp2 a

Kalman

----------------------------------------------------------------------
Get a free email address with REAL anti-spam protection.
http://www.bluebottle.com/tag/1



More information about the Haskell-Cafe mailing list