Can I "ensure" the members of data structure and not template
- cohen.avrahamOP
G-d willing
Assuming I have the following data structure:
data Test = Test num1 : Optional Int num2 : Optional IntHow can I ensure that I have a value in num1 or num2?
I cannot have both None or both with values… - Gary_Verhaegen 1
Hi @cohen.avraham,
If you must have either
num1ornum2(never none, never both), the way I’d approach the data type is:data SomeAppropriateName = FirstOption with value: Int | SecondOption with value: IntAnother option, which can sometimes be useful if you don’t want to go through the (actually very small, as illustrated above) trouble of creating your own data type for this, is to use the built-in
Eithertype. One thing of note here is that theEithertype has some additional semantics: in addition to being either aRightor aLeft, there is additional setup (typeclass implementations) to makeLeftsemantically represent errors, which may not be appropriate for all cases where you want a value that’s either one type or another. (But it’s very useful to have that already defined when you do want to represent “a successful result or an error message”.) - cohen.avraham
G-d willing
Thanks @Gary_Verhaegen for your response. The first option is better for me since sometimes it can be more than 2 options. Can you please show me an example how can I know what type do I have in it? How do I handle this type of data?
For example:data SomeAppropriateName = FirstOption with value: Int | SecondOption with value: Int | ThirdOption with value: Text - Gary_Verhaegen 1
This is where pattern matching comes in. Let’s say you have a function that needs to return the value if the argument is a
FirstOption, the value squared if it is aSecondOption, and 0 if it is aThirdOption. You’d write it something like:myFunction : SomeAppropriateName -> Int myFunction san = case san of FirstOption x -> x SecondOption x -> x * x ThirdOption _ -> 0You can find more about pattern matching in the “Data types” section of the Introduction to Daml series.