Can I "ensure" the members of data structure and not template

G-d willing

Assuming I have the following data structure:

data Test = Test
  num1 : Optional Int
  num2 : Optional Int

How can I ensure that I have a value in num1 or num2?
I cannot have both None or both with values…

Hi @cohen.avraham,

If you must have either num1 or num2 (never none, never both), the way I’d approach the data type is:

data SomeAppropriateName
 = FirstOption with value: Int
 | SecondOption with value: Int

Another 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 Either type. One thing of note here is that the Either type has some additional semantics: in addition to being either a Right or a Left, there is additional setup (typeclass implementations) to make Left semantically 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”.)

1 Like

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

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 a SecondOption, and 0 if it is a ThirdOption. You’d write it something like:

myFunction : SomeAppropriateName -> Int
myFunction san = case san of
  FirstOption x -> x
  SecondOption x -> x * x
  ThirdOption _ -> 0

You can find more about pattern matching in the “Data types” section of the Introduction to Daml series.

1 Like