3

Lets say i have

data A = B Char Integer

and I have a variable called var in type A. How can I access the integer value of var variable and use it? Is there any operator to get it? I don't know, something like var->int would give me it?

2 Answers 2

6

You can define a function for this using pattern matching:

getIntegerFromA :: A -> Integer
getIntegerFromA (B _ int) = int

Though depending on where you want to use it, you can probably get the value using pattern matching right there instead of defining a separate function.

Sign up to request clarification or add additional context in comments.

6 Comments

You can also have Haskell define what are referred to (somewhat confusingly for people coming from OO languages) as "destructors" for you: change the definition to data A = B {charval :: Char, intval :: Integer}. Now you can use intval var to get at it.
Nitpicking on @geekosaur's useful remark: It's "deconstructor", and the more confusing term to OO people is "constructor" (in OP's example, the B is one of potentially many constructors).
I think using pattern matching somehow makes more sense to me, but thanks for the answers.
@sepp2k: Untrue, B 'c' 5 still works, as does pattern matching against it. See the heading "Labelled Fields" in the Online Report.
@geekosaur: I think this is more commonly referred to as "record syntax".
|
1

The other way is to use "record syntax", which generates the accessor functions automatically, but many people consider ugly and un-Haskell like.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.