user686605
user686605

Reputation:

Deconstructing types in Haskell

I've defined the following type in Haskell:

data AE = Num Float
        | Add AE AE
        | Sub AE AE
        | Mult AE AE
        | Div AE AE
        deriving(Eq, Read, Show)

Now how do I deconstruct it? Specifically, how would I complete a function as follows:

testFunct :: AE -> something
testFunct expression
    | if type Num = do this
    | if type Add = then do this
    etc.

Also, how would I get the data out of the type? For instance, if I have Sub AE1 AE2 how would I extract AE2?

Upvotes: 4

Views: 3598

Answers (1)

bzn
bzn

Reputation: 2392

What you're looking for is called 'pattern matching'. It let's you deconstruct types, by matching them against a given pattern. In your case, you could say:

testFunct (Num x) = ...
testFunct (Add a b) = ...
testFunct (Sub a b) = ...

You should work through a good haskell book, like LYAH or Programming in Haskell.

Upvotes: 10

Related Questions