Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deconstructing types in Haskell

Tags:

types

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?


1 Answers

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.

like image 108
bzn Avatar answered Oct 22 '25 03:10

bzn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!