Is it possible to access a specific piece of a custom data type in Haskell?

I'm very new to haskell, and functional programming in general, I'm switching back and fourth between two different books on haskell, but I can't seem to find an answer to my question. Say I have a custom datatype like the one below

data Expr
  = Let String Expr Expr
  | Binary BinOp Expr Expr
  | Unary UnOp Expr
  | Literal Literal
  | Var String

and I have an instance of this data type that is in the form of the first constructor Let String Expr Expr, is it possible to access a specific piece of that Expr? For example if I wanted to access the String within that specific instance.

Upvotes: 1

Views: 888

Answers (1)

Adam Wagner
Adam Wagner

Reputation: 16087

Pattern matching is your answer.

Something like this should do the trick:

myfunction :: Expr -> SomeReturnType
myfunction (Let str _ _) = doSomethingWith str   -- "str" here is your string

You'll want to handle the other cases as well though, so you don't cause a runtime error:

myfunction :: Expr -> SomeReturnType
myfunction (Let str _ _) = doSomethingElse str
myfunction (Binary _ _ _) = somethingEvenDifferent
myfunction (Unary _ _) = etc
--- etc...

the _ just says to ignore the value at that position in the constructor.


Also, as @Bergi mentioned, there are many other places you can use pattern matching, like let or case statements, just always be sure to handle all the cases that your value could potentially be at that point in your program.

Upvotes: 4

Related Questions